Spring Boot2.x Web MVC 自定义异常处理
1.定义异常
public class AccountException extends RuntimeException {
public AccountException() {
super();
}
public AccountException(String message) {
super(message);
}
public AccountException(String message, Throwable cause) {
super(message, cause);
}
public AccountException(Throwable cause) {
super(cause);
}
}
2.定义异常处理器
@RestControllerAdvice
public class AccountExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AccountException.class)
Response handleControllerException(HttpServletResponse response, Throwable ex) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return Response.exception(ex.getMessage());
}
}
3.业务代码
抛出异常:
public Account createAccount(Account account) {
throw new AccountException("账务业务异常");
// return accountRepository.save(account);
}
本文详细介绍了如何在SpringBoot2.x中自定义异常处理流程。首先定义了一个AccountException异常类,然后创建了AccountExceptionHandler处理器来捕获并处理AccountException,最后在业务代码中演示了如何抛出自定义异常。

1014

被折叠的 条评论
为什么被折叠?



