@RestControllerAdvice全局异常捕捉

  • Post author:
  • Post category:其他


自定义异常EbException

public class EbException extends RuntimeException
{
    private final String UNKOWN_ERROR = "unknown.error";

    private String msg;

    private String errorDetail;

    private Integer errorCode = 10000;


    public EbException(String detail)
    {
        super(detail);
        this.errorDetail = detail;
        this.msg= I18nUtil.get(UNKOWN_ERROR);
    }


    public Integer getErrorCode()
    {
        return errorCode;
    }

    public String getMsg()
    {
        return msg;
    }

    public String getDetail()
    {
        return errorDetail;
    }

    public ResponseEntity<BaseResponse> toResponseEntity()
    {
        return ResponseEntity.ok().body(new BaseResponse<>(getErrorCode(), null, getMsg(), errorDetail));
    }
}

全局异常捕捉器

@RestControllerAdvice
@Slf4j
public class EbExceptionAdvice
{
    @ExceptionHandler(EbException.class)
    public final ResponseEntity<BaseResponse> handleKgServiceException(EbException ex, HttpServletRequest request)
    {
        log.error("Catch {} from controller, the request is {} {}", ex.getClass().getName(), request.getRequestURI(),ex);
        // print business-related stacktrace for troubleshooting
        log.debug("Exception trace {}", ex);
        return ex.toResponseEntity();
    }

    @ExceptionHandler(RuntimeException.class)
    public final ResponseEntity<BaseResponse> handleRuntimeException(RuntimeException ex, HttpServletRequest request)
    {
        log.error("Catch {} from controller, the request is {} {}", ex.getClass().getName(), request.getRequestURI(),ex);
        // print business-related stacktrace for troubleshooting
        log.info("Catch runtime exception");
        return ResponseEntity.ok().body(new BaseResponse<>(EbErrorCode.UNKNOWN_ERROR.getErrorCode(),
                null, I18nUtil.get(EbErrorCode.UNKNOWN_ERROR.getErrorMsg()), ex.getMessage()));
    }
}

定义异常码

public enum EbErrorCode
{
    //用户登录错误
    JWT_TOKEN_INVALID(90001, "ebauth.token.invalid"),
    JWT_TOKEN_EXPIRE(90002, "ebauth.token.expire"),
    USER_NOT_EXIST(90003, "ebauth.user.not.exist"),
    USER_DISABLED(90003, "ebauth.user.disabled"),
    TEAM_DISABLED(90004, "ebauth.team.disabled"),
    USER_AUTHORIZATION_ERROR(90005, "ebauth.user.authorization"),
    //

    AD_INPUT_MISSING(90005, "ebadauth.missing.input"),

    UNKNOWN_ERROR(100000, "unknown.error");

    private Integer errorCode;

    private String errorMsg;

    EbErrorCode(Integer errorCode, String errorMsg)
    {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public Integer getErrorCode()
    {
        return this.errorCode;
    }

    public String getErrorMsg() { return this.errorMsg; }
}

原理:被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping (@GetMapping等注解同理)注解的方法上。

参考:https://www.cnblogs.com/magicalSam/p/7198420.html



版权声明:本文为weixin_38611497原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。