SpringBoot自定义错误信息,SpringBoot自定义异常处理类,

SpringBoot异常结果处理适配页面及Ajax请求,

SpringBoot适配Ajax请求

================================

©Copyright 蕃薯耀 2018年3月29日

http://www.cnblogs.com/fanshuyao/

附件&源码下载见:http://fanshuyao.iteye.com/blog/2414865

一、自定义异常处理类:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.springframework.web.bind.annotation.ControllerAdvice;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import com.lqy.springboot.component.CustomErrorAttribute;
  7. @ControllerAdvice
  8. public class CustomExceptionHandler {
  9. /**
  10. * 自定义异常数据
  11. * 缺点,没有适配页面和Ajax请求,返回的数据都是json数据
  12. * @param req
  13. * @return
  14. */
  15. /*@ResponseBody
  16. @ExceptionHandler(Exception.class)
  17. public Map<String, Object> exceptionHandler(HttpServletRequest req){
  18. Map<String, Object> map = new HashMap<String, Object>();
  19. map.put("errorCode", 500);
  20. map.put("errorMsg", "错误信息");
  21. map.put("errorSystem", "errorSystem");
  22. return map;
  23. }*/
  24. /**
  25. * 自定义异常数据
  26. * 适配页面和Ajax请求
  27. * 注解ExceptionHandler(Exception.class)的Exception.class可以替换成自己定义的错误异常类
  28. * @param req
  29. * @return
  30. */
  31. @ExceptionHandler(Exception.class)
  32. public String exceptionHandler(HttpServletRequest req){
  33. Map<String, Object> map = new HashMap<String, Object>();
  34. map.put("errorCode", 500);
  35. map.put("errorMsg", "错误信息");
  36. map.put("errorSystem", "errorSystem");
  37. req.setAttribute(CustomErrorAttribute.CUSTOM_ERROR_MAP_NAME, map);
  38. //传入自己的错误代码,必须的,否则不会进入自定义错误页面,见:org.springframework.boot.autoconfigure.web.AbstractErrorController
  39. req.setAttribute("javax.servlet.error.status_code", 500);
  40. //转发到springBoot错误处理请求,能适配网页和Ajax的错误处理
  41. //请求/error后,会进入BasicErrorController(@RequestMapping("${server.error.path:${error.path:/error}}"))
  42. //页面的数据显示处理是使用:errorAttributes.getErrorAttributes获取显示的,是AbstractErrorController的方法
  43. //当需要把自己定义的Map错误信息传递到错误提示页面时,
  44. //可以编写一个自定义错误属性类处理:CustomErrorAttribute,继承DefaultErrorAttributes类,
  45. //重写getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace)方法
  46. return "forward:/error";
  47. }
  48. }

异常捕捉后请求转发到

  1. return "forward:/error";

是为了让SpringBoot底层处理,协助系统适配页面返回结果和Ajax返回结果:当是页面打开时,会跳转到相应的错误页面显示异常信息,当是Ajax请求或者使用工具请求时,返回的json字符串。(下面有图)

SpringBoot适配页面返回结果和Ajax返回结果的代码如下:

  1. @RequestMapping(produces = "text/html")
  2. public ModelAndView errorHtml(HttpServletRequest request,
  3. HttpServletResponse response) {
  4. HttpStatus status = getStatus(request);
  5. Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
  6. request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  7. response.setStatus(status.value());
  8. ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  9. return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  10. }
  11. @RequestMapping
  12. @ResponseBody
  13. public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  14. Map<String, Object> body = getErrorAttributes(request,
  15. isIncludeStackTrace(request, MediaType.ALL));
  16. HttpStatus status = getStatus(request);
  17. return new ResponseEntity<Map<String, Object>>(body, status);
  18. }

二、自定义异常信息传递类

  1. import java.util.Map;
  2. import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.context.request.RequestAttributes;
  5. @Component
  6. public class CustomErrorAttribute extends DefaultErrorAttributes {
  7. public static final String CUSTOM_ERROR_MAP_NAME = "customErrorMap";
  8. @Override
  9. public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
  10. Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
  11. //设置传递自己定义的错误信息
  12. map.put(CUSTOM_ERROR_MAP_NAME, requestAttributes.getAttribute(CUSTOM_ERROR_MAP_NAME, RequestAttributes.SCOPE_REQUEST));
  13. return map;
  14. }
  15. }

定义这个类,是为了传递自己想要显示的错误信息,例如在Controller发生错误时,想把某些特殊信息传到错误页面,就可以自定义一个异常信息处理类,传递自己的自定义错误信息,同时也兼容SpringBoot本身定义好的错误 信息。

三、页面显示异常信息

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>500</title>
  6. </head>
  7. <body>
  8. <div>500错误</div>
  9. <div>path:[[${path}]]</div>
  10. <div>status:[[${status}]]</div>
  11. <div>timestamp:[[${#dates.format(timestamp, 'yyyy-MM-dd HH:mm:ss')}]]</div>
  12. <div>error:[[${error}]]</div>
  13. <div>exception:[[${exception}]]</div>
  14. <div>message:[[${message}]]</div>
  15. <div>errors:[[${errors}]]</div>
  16. <!-- 自定义属性 -->
  17. <div>customErrorMap.errorMsg:[[${customErrorMap.errorMsg}]]</div>
  18. <div>customErrorMap.errorSystem:[[${customErrorMap.errorSystem}]]</div>
  19. <div>customErrorMap.errorCode:[[${customErrorMap.errorCode}]]</div>
  20. </body>
  21. </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请求的更多相关文章

  1. SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面

    SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...

  2. springboot自定义错误页面

    springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...

  3. 自定义错误信息并写入到Elmah

    在ap.net Web项目中一直使用Elmah进行日志记录, 但一直有一个问题困扰我很久,那就是我如何自己生成一个错误并记录到Elmah里去. 你知道有时你需要在项目中生成一个错误用于一些特殊的需求 ...

  4. 自定义 ocelot 中间件输出自定义错误信息

    自定义 ocelot 中间件输出自定义错误信息 Intro ocelot 中默认的 Response 中间件在出错的时候只会设置 StatusCode 没有具体的信息,想要展示自己定义的错误信息的时候 ...

  5. 前端:参数传错了,spring-boot:那错误信息我给你显示的友好点儿

    之前两篇文章 Spring-boot自定义参数校验注解和如何在spring-boot中进行参数校验,我们介绍了,参数校验以及如何自定义参数校验注解,但是当传递参数出错时,只是把错误信息打印到了控制台, ...

  6. ASP.NET MVC 中如何用自定义 Handler 来处理来自 AJAX 请求的 HttpRequestValidationException 错误

    今天我们的项目遇到问题 为了避免跨站点脚本攻击, 默认我们项目是启用了 validateRequest,这也是 ASP.NET 的默认验证规则.项目发布后,如果 customError 启用了,则会显 ...

  7. Springboot - 自定义错误页面

    Springboot 没找到页面或内部错误时,会访问默认错误页面.这节我们来自定义错误页面. 自定义错误页面 1.在resources 目录下面再建一个 resources 文件夹,里面建一个 err ...

  8. springboot自定义错误页面(转)

    方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController @Controller @RequestMapping(value = "error ...

  9. jquery.validate使用 - 自定义错误信息

    自定义错误消息的显示方式 默认情况下,验证提示信息用label元素来显示, 并且会添加css class, 通过css可以很方便设置出错控件以及错误信息的显示方式. /* 输入控件验证出错*/form ...

随机推荐

  1. 使用 IntraWeb (35) - TIWJQueryWidget

    可有可无的东西, 因为没有它也可以方便达成其目的, 使用它貌似更形象一些; 也可以通过它调用其他 js 库. 利用类似手段, 有人推出了 CGDevTools; 它主要是利用 JQuery 扩展而成, ...

  2. Reactor 3 学习笔记(2)

    接上篇继续学习各种方法: 4.9.reduce/reduceWith @Test public void reduceTest() { Flux.range(1, 10).reduce((x, y) ...

  3. elastic-job 新手指南

    大多数情况下,定时任务我们一般使用quartz开源框架就能满足应用场景.但如果考虑到健壮性等其它一些因素,就需要自己下点工夫,比如:要避免单点故障,至少得部署2个节点吧,但是部署多个节点,又有其它问题 ...

  4. JS Range使用整理

    1.获取用户网页选中内容 <p>4月13日消息,据台湾媒体报道,32岁的孙燕姿(Sng Ee Tze)和后天将满34岁的荷兰籍印度尼西亚男友纳迪姆(Nadim Van Der Ros)交往 ...

  5. 坚果云无法同步SVN文件夹

    把svn的库放在云盘上,同步到本地,以前在金山快盘.360网盘都用得好好的,换坚果云后,想着肯定没问题,结果发现,不行! 新机子上的版本库可以建起来,但检出时报错: Could not open th ...

  6. webservice 配置

    webservice 配置 <system.web> <!--允许GET/POST请求 --> <webServices> <protocols> &l ...

  7. 微软BI 之SSIS 系列 - 两种将 SQL Server 数据库数据输出成 XML 文件的方法

    开篇介绍 在 SSIS 中并没有直接提供从数据源到 XML 的转换输出,Destination 的输出对象有 Excel File, Flat File, Database 等,但是并没有直接提供 X ...

  8. 【NIO】Java NIO之通道

    一.前言 前面学习了缓冲区的相关知识点,接下来学习通道. 二.通道 2.1 层次结构图 对于通道的类层次结构如下图所示. 其中,Channel是所有类的父类,其定义了通道的基本操作.从 Channel ...

  9. ZOJ 3827 Information Entropy 水

    水 Information Entropy Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge Informati ...

  10. 【Linux】linux/unix下telnet提示Escape character is '^]'的意义

    在linux/unix下使用telnet hostname port连接上主机后会提示Escape character is '^]' 这个提示的意思是按Ctrl + ] 会呼出telnet的命令行, ...