Spring web 异常统一处理
2020-06-18 本文已影响0人
wenyu7980
异常类型
- 检查异常
检查异常需要捕获或者在函数签名中抛出异常,一般是IO异常,通常处理方式是,如果需要重试则try cach再试,如果不需要处理,则转为非检查异常,或者是在追加到函数签名中。
- 非检查异常
不需要额外处理
使用@RestControllerAdvice统一处理异常
@RestControllerAdvice
public class ExceptionHandlerConfiguration {
private static final Logger LOGGER = LoggerFactory
.getLogger(ExceptionHandlerConfiguration.class);
@ExceptionHandler(Exception.class)
public ResponseEntity<ResultBody> handler(Exception e) {
if (e instanceof AbstractException) {
AbstractException exception = (AbstractException) e;
if (exception instanceof SystemException) {
LOGGER.error("开发异常", e);
} else {
LOGGER.debug("异常", e);
}
return new ResponseEntity<ResultBody>(
ResultBody.failed().code(exception.getCode())
.msg(e.getMessage()),
HttpStatus.INTERNAL_SERVER_ERROR);
}
LOGGER.error("系统错误", e);
return new ResponseEntity<ResultBody>(
ResultBody.failed().code(ErrorCode.ERROR.getCode())
.msg(e.getMessage() + Arrays
.toString(e.getStackTrace())),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
抽象异常
public abstract class AbstractException extends RuntimeException {
private Integer code;
public AbstractException(Integer code, String message, Object... params) {
super(MessageFormat.format(message, params));
this.code = code;
}
public AbstractException(ErrorCode code, String message, Object... params) {
super(MessageFormat.format(message, params));
this.code = code.getCode();
}
public Integer getCode() {
return code;
}
}
业务异常
image.png
例如
public class RequestBodyBadException extends AbstractException {
public RequestBodyBadException(String message, Object... params) {
super(ErrorCode.BAD_REQUEST, message, params);
}
}