标签:exception,return,记录,ApiResult,ERROR,result,error,全局,异常 From: https://www.cnblogs.com/javalbb/p/17099029.html
/**
* 全局异常处理类,能够处理到controller、filter、interceptro所抛出的异常
* 不使用HandlerExceptionResolver、结合两者使用(ControllerAdvice|ErrorController)
*/
@RestControllerAdvice
@Controller
public class GlobleAdviceAndErrorController implements ErrorController {
Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String ERROR_PATH="/error";
@RequestMapping(ERROR_PATH)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ApiResult<Object> error(HttpServletRequest request, HttpServletResponse response) {
//获取错误信息
Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
// Object servlet_name = request.getAttribute("javax.servlet.error.servlet_name");
// Object message = request.getAttribute("javax.servlet.error.message");
// String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
if (status > 400 && status < 500) {
response.setStatus(200);
return ApiResult.error(status.toString(), "请求无效");
}
if (exception==null){
return ApiResult.error(status.toString(), "请求无效");
}
if (status == 400) {
return ApiResult.error(status.toString(), exception.getMessage());
}
return buildErrorResult(exception);
}
@ExceptionHandler(Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ApiResult<Object> handleExeption(Exception ex) {
return buildErrorResult(ex);
}
//处理自定义(业务逻辑错误)异常,不需要记录日志
@ExceptionHandler(BaseException.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ApiResult<Object> handleBaseExeption(BaseException ex) {
logger.error("业务异常code:{},{}",ex.getCode(),ex.getMessage());
return new ApiResult<>(ex.getCode(),ex.getMessage());
}
private ApiResult<Object> buildErrorResult(Throwable exception) {
ApiResult result = new ApiResult();
String err_code = java.util.UUID.randomUUID().toString();
//返回值
if (exception != null) {
BaseException baseException = null;
if (exception instanceof BaseException) {
baseException = (BaseException) exception;
} else if (exception.getCause() instanceof BaseException) {
baseException = (BaseException) exception.getCause();
}else if (exception instanceof MethodArgumentNotValidException){
baseException= new BaseException(ExceptionCodeEnum.PARAMETER_ERROR.getCode(),exception.getMessage());
} else if (exception.getCause() instanceof RuntimeException) {
//baseException = new BaseException(ResultCodeEnum.SERVER_INTERNAL_ERROR.getCode() + "", exception.getCause().getMessage());
baseException = new BaseException(ResultCodeEnum.SERVER_INTERNAL_ERROR.getCode() + "", "编号[" + err_code + "]");
} else {
baseException = new BaseException(ResultCodeEnum.SERVER_INTERNAL_ERROR.getCode() + "", "编号[" + err_code + "]");
}
result.setCode(baseException.getCode());
result.setMessage(baseException.getMessage());
} else {
result.setCode(ResultCodeEnum.SERVER_INTERNAL_ERROR.getCode());
}
result.setData("编号[" + err_code + "]");
recodeExceptionLog(result, exception);
return result;
}
/**
* 记录错误日志
*
* @param result
* @param exception
*/
private void recodeExceptionLog(ApiResult<Object> result, Throwable exception) {
String errorMsg = "错误日志:";
errorMsg += result.getCode() + ";" + result.getMessage() + "\r\n";
errorMsg += result.getData();
errorMsg += exception.getStackTrace()[0];
logger.error(errorMsg,exception);
}
/**
* 校验错误拦截处理
*
* @param exception 错误信息集合
* @return 错误信息
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResult validationBodyException(MethodArgumentNotValidException exception){
BindingResult result = exception.getBindingResult();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
//取第一个
String message = errors.stream().map(e -> ((FieldError) e).getDefaultMessage()).filter(e->!StringUtils.isEmpty(e)).findFirst().get();
if (!StringUtils.isEmpty(message)){
return ApiResult.error(ExceptionCodeEnum.PARAMETER_ERROR,message);
}
}
return ApiResult.error(ExceptionCodeEnum.PARAMETER_ERROR,"请填写正确信息");
}
/**
* 参数类型转换错误
*
* @param exception 错误
* @return 错误信息
*/
@ExceptionHandler(HttpMessageConversionException.class)
public ApiResult parameterTypeException(HttpMessageConversionException exception){
logger.error("参数类型转换错误",exception);
//logger.error(exception.getCause().getLocalizedMessage()!=null?exception.getCause().getLocalizedMessage():exception.getMessage());
return ApiResult.error(ExceptionCodeEnum.PARAMETER_ERROR);
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}