class类上添加注解@RestControllerAdvice
方法上添加注解:@ExceptionHandler(Exception.class)
@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result<?> exception(Exception e) {
String location = Arrays.stream(e.getStackTrace()).skip(200).filter(t -> t.getClassName().startsWith(“com.hkhp.”))
.map(t -> “class:” + t.getClassName() + “,methodName:” + t.getMethodName() + “,lineNumber:” + t.getLineNumber()).collect(Collectors.joining(","));
log.error(“error:location:{},message:{}”, location, e.getMessage(), e);
if (e instanceof HttpMessageNotReadableException) {
return Result.fail(501, “请求入参错误”);
}
if (e instanceof MissingServletRequestParameterException) {
return Result.fail(502, “请求入参错误”);
}
if (e instanceof ParamException) {
return ((ParamException) e).getResult();
}
if (e instanceof ValueException) {
return ((ValueException) e).getResult();
}
if (e instanceof BizException) {
return ((BizException) e).getResult();
}
if (e instanceof JsonMappingException) {
return Result.fail(503).setMessage(“请求解析错误”);
}
return Result.fail(500).setMessage(“请求处理失败或重复请求,请稍候再试”).setExceptionMsg(e.getLocalizedMessage());
}
}