springboot rest介面404和500的特殊處理
阿新 • • 發佈:2018-12-03
首先新增全域性異常處理:
@ControllerAdvice @Slf4j public class GlobalExceptionHandler { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @ExceptionHandler({BaseException.class, HttpMessageNotReadableException.class, HttpMediaTypeNotSupportedException.class, MaxUploadSizeExceededException.class, HttpRequestMethodNotSupportedException.class, MethodArgumentNotValidException.class, BindException.class,}) Object serverExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) { MsgCode msgCode; BaseException baseException = null; response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); Response result; if (e instanceof BaseException) { baseException = (BaseException) e; msgCode = baseException.getMsgCode(); result = ResponseUtil.fail(Collections.EMPTY_MAP, msgCode, baseException.getMessage()); } else if (e instanceof HttpMessageNotReadableException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, "缺少必須的引數"); } else if (e instanceof HttpMediaTypeNotSupportedException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, "請求型別不匹配"); } else if (e instanceof MaxUploadSizeExceededException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, "請不要上傳超過10MB的檔案"); } else if (e instanceof HttpRequestMethodNotSupportedException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, "不支援該型別的請求"); } else if (e instanceof MethodArgumentNotValidException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage()); } else if (e instanceof BindException) { result = ResponseUtil.fail(Collections.EMPTY_MAP, ((BindException) e).getBindingResult().getFieldError().getDefaultMessage()); } else { result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD); } log.error("異常資訊:{}", Optional.ofNullable(baseException).filter(e1 -> e1.getMsgCode() != null).map(b -> b.getMsgCode().getMessage()).orElse(e.getMessage())); e.printStackTrace(); try (PrintWriter printWriter = response.getWriter()) { printWriter.write(OBJECT_MAPPER.writeValueAsString(result)); } catch (IOException e1) { } return null; } @ExceptionHandler(value = Exception.class) @ResponseBody public Object defaultErrorHandler(Exception e) { if (e instanceof NoHandlerFoundException) { return ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_NOTFOUND); } else { return ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD); } }
在application.yml中新增以下配置來告訴springboot不要建預設的資源對映
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false