创建拦截器类并标注@ControllerAdvice注解

@ControllerAdvice
public class GlobalExceptionAdvice {

    //处理未知异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public UnifyResponse handleException(HttpServletRequest request, Exception e){
        String method = request.getMethod();
        String requestUrl = request.getRequestURI();
        System.out.println(method);
        System.out.println(requestUrl);
        System.out.println(e);
        UnifyResponse unifyResponse = new UnifyResponse(9999, "服务器异常", requestUrl + " " + method);
        return unifyResponse;
    }
}
public class UnifyResponse {

    private Integer code;
    private String message;
    private String request;

    public UnifyResponse(Integer code, String message, String request) {
        this.code = code;
        this.message = message;
        this.request = request;
    }

    public UnifyResponse(){

    }


    @Override
    public String toString() {
        return "UnifyResponse{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", request='" + request + '\'' +
                '}';
    }

    /**
     * 使用抛出异常的方式表示请求成功
     */
    public static void crreateSuccess(){
        throw new CreateSuccess(1);
    }
}

在类中创建对异常的处理方法

  • @ExceptionHandler:指出该方法会处理哪些异常。
  • @ResponseStats:指定返回前端的错误码。

通过request与exception参数可获得请求与异常信息,并决定返回前端的错误信息。
以上方法基本可以满足大部分需求,但对于灵活调整返回前端的http错误码还是不太方便,需要对应每个http错误码建立不同的处理方法。

实现决定返回前端的消息的http错误码

public class HttpException extends RuntimeException{

    protected Integer code;
    protected Integer httpStatusCode = 500;

    public Integer getCode() {
        return code;
    }

    public Integer getHttpStatusCode() {
        return httpStatusCode;
    }
}
public class NotFoundException extends HttpException{

    public NotFoundException(int code){
        this.code = code;
        this.httpStatusCode = 404;
    }
}

我采用创建一个Http异常基类继承RuntimeException,然后根据不同的http错误码创建不同的异常类实现HttpException,并传入自己的错误码,不传入错误码则默认使用500

@ExceptionHandler(HttpException.class)
    public ResponseEntity handleHttpException(HttpServletRequest request, HttpException e){
        String method = request.getMethod();
        String requestUrl = request.getRequestURI();
        UnifyResponse unifyResponse = new UnifyResponse(e.getCode(), requestUrl + " " + method);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpStatus httpStatus = HttpStatus.resolve(e.getHttpStatusCode());
        ResponseEntity<UnifyResponse> responseEntity = new ResponseEntity(unifyResponse, headers, httpStatus);
        return responseEntity;
    }

创建新的方法处理自定异常,为了改变返回消息的错误码需要设置http头部,并创建ResponseEntity将http头部与http错误码对象传入后返回。


guomz
16 声望1 粉丝

不求做完人,只求做凡人。