我正在实施 2 个 ControllersAdvice。处理异常 CommonAdvice 和 UserAdvice
常见建议
@ControllerAdvice(annotations = RestController.class)
public class CommonAdvice {
@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionBean> handleException(Exception e) {
ExceptionBean exception = new ExceptionBean(Causes.ANOTHER_CAUSE);
return new ResponseEntity<ExceptionBean>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Run Code Online (Sandbox Code Playgroud)
用户建议
@ControllerAdvice(assignableTypes = { requestUserMapper.class })
public class UserAdvice {
@ExceptionHandler(NotUniqueUserLoginException.class)
public ResponseEntity<ExceptionBean> handleAlreadyFound(NotUniqueUserLoginException e) {
System.out.println("this is me : " + Causes.USER_ALREADY_EXIST.toString());
ExceptionBean exception = new ExceptionBean(Causes.USER_ALREADY_EXIST);
return new ResponseEntity<ExceptionBean>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}
Run Code Online (Sandbox Code Playgroud)
现在,当我抛出 NotUniqueUserException 时,这是一个处理异常的 CommonAdvice。
我测试过,UserAdvice 工作正常。有办法设置这个类的优先级吗?
@Edit - 添加控制映射
@RequestMapping(value = "add", method = RequestMethod.POST)
public ResponseEntity<GT_User> addUser(@RequestBody GT_User newUser) throws NotUniqueUserLoginException, Exception {
if (this.userService.exist(newUser.getLogin())) {
throw new NotUniqueUserLoginException(Causes.USER_ALREADY_EXIST.toString());
} else {
GT_User addesUser = this.userService.addUser(newUser);
return new ResponseEntity<GT_User>(addesUser, HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
要在添加时为 ControllerAdvice 设置更高的优先级:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import com.genealogytree.webapplication.dispatchers.requestUserMapper;
@ControllerAdvice(assignableTypes = { requestUserMapper.class })
@Order(Ordered.HIGHEST_PRECEDENCE)
public class UserAdvice {
...
}
Run Code Online (Sandbox Code Playgroud)
添加时将较低优先级设置为 ControolerAdvice
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import com.genealogytree.webapplication.dispatchers.requestUserMapper;
@ControllerAdvice(assignableTypes = { requestUserMapper.class })
@Order(Ordered.LOWEST_PRECEDENCE)
public class CommonAdvice {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4350 次 |
| 最近记录: |