在SpringBoot默认的异常处理是返回一个HTML页面,但是在前后端分离的开发模式下,服务器出现异常应该以json格式返回数据给前端。
@ControllerAdvicepublic class GlobalExceptionAdvice { // 捕获所有异常 @ExceptionHandler(Exception.class) // 以rest方式响应给客户端 @ResponseBody public Object exceptionHandler(Exception e){ Map map = new HashMap<>(); map.put("error", e.getMessage()); map.put("status", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); map.put("exception", e.getClass().getName()); map.put("timestamp", new Date()); HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest(); HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getResponse(); map.put("path", request.getRequestURI()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return map; }}