Spring Boot2.x 自定义异常处理

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);
    }

你可能感兴趣的:(Spring,Boot)