/** * 处理统一返回异常 */ @ControllerAdvice public class GlobalExceptionHandler { private final Logger log= LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(SunyardException.class) @ResponseBody public Object handleSunyardException(SunyardException e){ log.error("SunyardException:",e); return ApiRestResponse.error(e.getCode(),e.getMsg()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ApiRestResponse handleMethodArgumentNotValidException( MethodArgumentNotValidException e){ log.error("MethodArgumentNotValidException:",e); return handleBindingResult(e.getBindingResult()); } @ExceptionHandler(Exception.class) @ResponseBody public Object handleException(Exception e){ log.error("Default Exception: ",e); return ApiRestResponse.error(SunyardExceptionEnum.SYSTEM_ERROR); } private ApiRestResponse handleBindingResult(BindingResult result){ //把异常处理为对外暴露提示 List<String> list=new ArrayList<>(); if (result.hasErrors()){ List<ObjectError> allErrors = result.getAllErrors(); for (ObjectError objectError:allErrors){ String message = objectError.getDefaultMessage(); list.add(message); } } if (list.size()==0){ return ApiRestResponse.error(SunyardExceptionEnum.PARAMS_ERROR); } return ApiRestResponse.error(SunyardExceptionEnum.PARAMS_ERROR.getCode(),list.toString()); } }
统一返回异常
最新推荐文章于 2024-07-13 18:11:28 发布