SpringBoot自定义错误信息,SpringBoot适配Ajax请求
SpringBoot自定义错误信息,SpringBoot自定义异常处理类,
SpringBoot异常结果处理适配页面及Ajax请求,
SpringBoot适配Ajax请求
================================
©Copyright 蕃薯耀 2018年3月29日
http://www.cnblogs.com/fanshuyao/
附件&源码下载见:http://fanshuyao.iteye.com/blog/2414865
一、自定义异常处理类:
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import com.lqy.springboot.component.CustomErrorAttribute;
- @ControllerAdvice
- public class CustomExceptionHandler {
- /**
- * 自定义异常数据
- * 缺点,没有适配页面和Ajax请求,返回的数据都是json数据
- * @param req
- * @return
- */
- /*@ResponseBody
- @ExceptionHandler(Exception.class)
- public Map<String, Object> exceptionHandler(HttpServletRequest req){
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("errorCode", 500);
- map.put("errorMsg", "错误信息");
- map.put("errorSystem", "errorSystem");
- return map;
- }*/
- /**
- * 自定义异常数据
- * 适配页面和Ajax请求
- * 注解ExceptionHandler(Exception.class)的Exception.class可以替换成自己定义的错误异常类
- * @param req
- * @return
- */
- @ExceptionHandler(Exception.class)
- public String exceptionHandler(HttpServletRequest req){
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("errorCode", 500);
- map.put("errorMsg", "错误信息");
- map.put("errorSystem", "errorSystem");
- req.setAttribute(CustomErrorAttribute.CUSTOM_ERROR_MAP_NAME, map);
- //传入自己的错误代码,必须的,否则不会进入自定义错误页面,见:org.springframework.boot.autoconfigure.web.AbstractErrorController
- req.setAttribute("javax.servlet.error.status_code", 500);
- //转发到springBoot错误处理请求,能适配网页和Ajax的错误处理
- //请求/error后,会进入BasicErrorController(@RequestMapping("${server.error.path:${error.path:/error}}"))
- //页面的数据显示处理是使用:errorAttributes.getErrorAttributes获取显示的,是AbstractErrorController的方法
- //当需要把自己定义的Map错误信息传递到错误提示页面时,
- //可以编写一个自定义错误属性类处理:CustomErrorAttribute,继承DefaultErrorAttributes类,
- //重写getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace)方法
- return "forward:/error";
- }
- }
异常捕捉后请求转发到
- return "forward:/error";
是为了让SpringBoot底层处理,协助系统适配页面返回结果和Ajax返回结果:当是页面打开时,会跳转到相应的错误页面显示异常信息,当是Ajax请求或者使用工具请求时,返回的json字符串。(下面有图)
SpringBoot适配页面返回结果和Ajax返回结果的代码如下:
- @RequestMapping(produces = "text/html")
- public ModelAndView errorHtml(HttpServletRequest request,
- HttpServletResponse response) {
- HttpStatus status = getStatus(request);
- Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
- request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
- response.setStatus(status.value());
- ModelAndView modelAndView = resolveErrorView(request, response, status, model);
- return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
- }
- @RequestMapping
- @ResponseBody
- public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
- Map<String, Object> body = getErrorAttributes(request,
- isIncludeStackTrace(request, MediaType.ALL));
- HttpStatus status = getStatus(request);
- return new ResponseEntity<Map<String, Object>>(body, status);
- }
二、自定义异常信息传递类
- import java.util.Map;
- import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestAttributes;
- @Component
- public class CustomErrorAttribute extends DefaultErrorAttributes {
- public static final String CUSTOM_ERROR_MAP_NAME = "customErrorMap";
- @Override
- public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
- Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
- //设置传递自己定义的错误信息
- map.put(CUSTOM_ERROR_MAP_NAME, requestAttributes.getAttribute(CUSTOM_ERROR_MAP_NAME, RequestAttributes.SCOPE_REQUEST));
- return map;
- }
- }
定义这个类,是为了传递自己想要显示的错误信息,例如在Controller发生错误时,想把某些特殊信息传到错误页面,就可以自定义一个异常信息处理类,传递自己的自定义错误信息,同时也兼容SpringBoot本身定义好的错误 信息。
三、页面显示异常信息
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>500</title>
- </head>
- <body>
- <div>500错误</div>
- <div>path:[[${path}]]</div>
- <div>status:[[${status}]]</div>
- <div>timestamp:[[${#dates.format(timestamp, 'yyyy-MM-dd HH:mm:ss')}]]</div>
- <div>error:[[${error}]]</div>
- <div>exception:[[${exception}]]</div>
- <div>message:[[${message}]]</div>
- <div>errors:[[${errors}]]</div>
- <!-- 自定义属性 -->
- <div>customErrorMap.errorMsg:[[${customErrorMap.errorMsg}]]</div>
- <div>customErrorMap.errorSystem:[[${customErrorMap.errorSystem}]]</div>
- <div>customErrorMap.errorCode:[[${customErrorMap.errorCode}]]</div>
- </body>
- </html>
页面显示结果:

Post请求结果:

项目源码见附件:SpringBoot-自定义错误.zip
======SpringBoot自定义错误页面见:======
SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面
SpringBoot 4xx.html、5xx.html错误提示页面
http://www.cnblogs.com/fanshuyao/p/8668072.html
================================
©Copyright 蕃薯耀 2018年3月29日
http://www.cnblogs.com/fanshuyao/
SpringBoot自定义错误信息,SpringBoot适配Ajax请求的更多相关文章
- SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面
SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...
- springboot自定义错误页面
springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...
- 自定义错误信息并写入到Elmah
在ap.net Web项目中一直使用Elmah进行日志记录, 但一直有一个问题困扰我很久,那就是我如何自己生成一个错误并记录到Elmah里去. 你知道有时你需要在项目中生成一个错误用于一些特殊的需求 ...
- 自定义 ocelot 中间件输出自定义错误信息
自定义 ocelot 中间件输出自定义错误信息 Intro ocelot 中默认的 Response 中间件在出错的时候只会设置 StatusCode 没有具体的信息,想要展示自己定义的错误信息的时候 ...
- 前端:参数传错了,spring-boot:那错误信息我给你显示的友好点儿
之前两篇文章 Spring-boot自定义参数校验注解和如何在spring-boot中进行参数校验,我们介绍了,参数校验以及如何自定义参数校验注解,但是当传递参数出错时,只是把错误信息打印到了控制台, ...
- ASP.NET MVC 中如何用自定义 Handler 来处理来自 AJAX 请求的 HttpRequestValidationException 错误
今天我们的项目遇到问题 为了避免跨站点脚本攻击, 默认我们项目是启用了 validateRequest,这也是 ASP.NET 的默认验证规则.项目发布后,如果 customError 启用了,则会显 ...
- Springboot - 自定义错误页面
Springboot 没找到页面或内部错误时,会访问默认错误页面.这节我们来自定义错误页面. 自定义错误页面 1.在resources 目录下面再建一个 resources 文件夹,里面建一个 err ...
- springboot自定义错误页面(转)
方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController @Controller @RequestMapping(value = "error ...
- jquery.validate使用 - 自定义错误信息
自定义错误消息的显示方式 默认情况下,验证提示信息用label元素来显示, 并且会添加css class, 通过css可以很方便设置出错控件以及错误信息的显示方式. /* 输入控件验证出错*/form ...
随机推荐
- ecshop 添加后台页面以及设置权限
转自 http://blog.csdn.net/tgh1981/article/details/10394059 ecshop 添加新页面 给ecshop后台增加管理功能页面 比如我们增加一个统计报表 ...
- HttpServerProvider实现http服务接口(一)
啥也不说了,直接上代码,简单的示例. 服务端代码: package dyan.server; import java.io.BufferedReader; import java.io.IOExcep ...
- __x__(2)0905第二天__计算机软件和硬件
计算机(Computer)由硬件和软件组件,没有软件的计算机称为 裸机, 计算机的软件包括操作系统(OS)和应用软件(Software). 操作系统(Operating System,简称OS) 是管 ...
- RouterOS双线进行IP分流上网
环境: 1.第一条:电信静态IP,一级路由分配的IP:第二条:移动光纤 2.通过指定某些IP走电信,某些走移动 注意: 1.当有多条线路进行NAT伪装时,Out. Interface这个必须选择具体的 ...
- windows 2003 iis 360防黑加固后不能使用
最近在使用360的防黑加固加固2003系统,发现IIS居然不能够使用了,报401.1错误,查找解决方案如下: 1.我的电脑-〉属性-〉管理-〉本地用户和组,查看IUSER用户是否开启,如果未开启开启后 ...
- Vert.x入门教程之Hello World
http://blog.csdn.net/caihuangshi/article/details/51648182
- 【T07】不要低估tcp的性能
1.tcp在ip的基础上增加了校验和.可靠性和流量控制的功能,而udp只增加了校验和的功能,看起来udp应该会比tcp快很多, 但事实不是这样,有时候tcp比udp的性能还要好. 2.思考,在什么情况 ...
- 2D游戏新手引导点光源和类迷雾实现
一.新手引导须要的遮罩效果 一般做新手引导的时候,会把游戏画面变的半黑,然后须要玩家点击的地方就亮起来.经常使用的做法是採用遮罩来实现,可是仅仅能实现方形的,不能不规则图形.以及是全然挖空.做不到渐变 ...
- 摄像专用的SD卡推荐
此类SD卡主要需要满足快速写入:特别对于4K的支持,速度要有很高才能满足. 文章来源:刘俊涛的博客 欢迎关注,有问题一起学习欢迎留言.评论
- prestashop nginx rewrite rule
server { listen *:; server_name www.mydomain.com *.mydomain.com; root /var/www/www.mydomain.com/web; ...