SpringBoot自定义404、500返回JSON数据 以你之姓@ 2021-11-04 17:22 639阅读 0赞 # SpringBoot自定义404、500返回JSON数据 # 现有的方法,编写全局的异常处理,需要在SpringBoot配置文件中配置没有找到Controller时抛出异常,并且将静态资源映射关闭。因为默认是不抛出异常的,是去找错误页面,所以还需要关闭静态资源映射。但是这样就无法访问静态资源了。以下是解决方法。 当未找到页面时,会调用默认的Controller,就是这个没有值的RequestMapping。 在这个Controller中手动抛出异常,实际这里应该写switch语句,根据不同的错误抛出不同的异常,暂时没时间改。 自定义默认Controller @Controller public class DefaultController { @RequestMapping public void error(HttpServletRequest request) throws NoHandlerFoundException { throw new NoHandlerFoundException(request.getMethod(),request.getRequestURI(),new HttpHeaders()); } } 在这里编写全局的异常处理,使用自定义的返回结构返回数据。 @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handlerException(Exception e) { if (e instanceof NoHandlerFoundException) { ResultBean resultBean = new ResultBean(DEV_CODE_NOTFOUND,DEV_MSG_RESOURCE_NOT_FOUND,LOCALE_MSG_RESOURCE_NOT_FOUND); return resultBean.getResult(); } else { e.printStackTrace(); return new ResultBean(DEV_CODE_FAIL,e.getMessage(),LOCALE_MSG_SYSTEM_ERROR).getResult(); } } } 自定义JSON返回结构 public class ResultBean { private int code; private String devMsg; private String msg; private String data; public ResultBean(int code, String devMsg, String msg, String data) { this.code = code; this.devMsg = devMsg; this.msg = msg; this.data = data; } public ResultBean(int code, String devMsg, String msg) { this.code = code; this.devMsg = devMsg; this.msg = msg; this.data = ""; } public String getResult() { JSONObject jsonObject = new JSONObject(); jsonObject.put("code",code); jsonObject.put("devMsg",devMsg); jsonObject.put("msg",msg); jsonObject.put("data",data); return jsonObject.toString(); } } 配置没有找到Controller时抛出异常,理论上这个是非必须的,有待考证。 #出现错误时, 直接抛出异常 spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false
还没有评论,来说两句吧...