共计 2173 个字符,预计需要花费 6 分钟才能阅读完成。
创建拦截器类并标注 @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 错误码对象传入后返回。
正文完