SpringBoot默认有自定义异常处理的体系,在做SpringBoot项目的时候,如果是抛出了运行时异常,springBoot并会对异常进行处理,返回如下异常信息:

{
"timestamp": 1517294278132,
"status": 500,
"error": "Internal Server Error",
"exception": "com.lgy.common.exception.BusinessException",
"message": "[001]自定义的uncheck 异常!",
"path": "/validateExceptionTest"
}

追究其原因,发现SpirngBoot出现异常信息时候,会默认访问/error,springBoot种有BasicErrorController这个类来处理异常信息:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package org.springframework.boot.autoconfigure.web; import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties; public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
this(errorAttributes, errorProperties, Collections.emptyList());
} public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorViewResolvers);
Assert.notNull(errorProperties, "ErrorProperties must not be null");
this.errorProperties = errorProperties;
} public String getErrorPath() {
return this.errorProperties.getPath();
} @RequestMapping(
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = this.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 = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = this.getStatus(request);
return new ResponseEntity(body, status);
} protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
IncludeStacktrace include = this.getErrorProperties().getIncludeStacktrace();
return include == IncludeStacktrace.ALWAYS?true:(include == IncludeStacktrace.ON_TRACE_PARAM?this.getTraceParameter(request):false);
} protected ErrorProperties getErrorProperties() {
return this.errorProperties;
}
}

如果要取代SpringBoot默认的异常处理信息方式,继承ErrorController:

package com.lgy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import java.util.Map; /**
* Created by fengch on 2018/1/30.
*/
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class FundaErrorController implements ErrorController {
private static final String PATH = "/error"; @Autowired
private ErrorAttributes errorAttributes; @Override
public String getErrorPath() {
return PATH;
} @RequestMapping
@ResponseBody
public JSONObject doHandleError(HttpServletRequest request) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String,Object> errorAttributesData = errorAttributes.getErrorAttributes(requestAttributes,true);
Integer status=(Integer)errorAttributesData.get("status"); //状态码
String path=(String)errorAttributesData.get("path"); //请求路径
String messageFound=(String)errorAttributesData.get("message"); //异常信息 JSONObject reData = new JSONObject();
reData.put("status_", status);
reData.put("path_", path);
reData.put("message", messageFound);
return reData;
}
}

接着在访问,并是自定义处理的异常信息了:

{
"message": "[001]自定义的uncheck 异常!",
"path_": "/validateExceptionTest",
"status_": 500
}

转载

 

springboot 默认异常处理的更多相关文章

  1. java框架之SpringBoot(7)-异常处理

    前言 在 SpringBoot 项目中,默认情况下,使用浏览器访问一个不存在的地址会返回如下错误页面: 而当客户端未非浏览器时,错误信息则会以 json 数据返回,如下: 会出现如上效果的原因是 Sp ...

  2. springboot 全局异常处理

    springboot 全局异常处理 研究了半天springboot的全局异常处理,虽然还是需要再多整理一下,但是对于常见的404和500足以可以区分开,能够根据这两个异常分别处理 首先配置视图解析路径 ...

  3. Springboot的异常处理与自定义异常

    园友们好,元旦很快就到来了,提前祝各位园友们元旦快乐,今天给大家分享一个工作中必用一个知识点,就是使用枚举构建自定义异常并应用于springboot的异常处理器.开始之前我先把这个案例的结构大致说明一 ...

  4. springboot默认创建的bean是单实还是多例

    转:https://blog.csdn.net/q1512451239/article/details/53122687 springboot默认创建的bean是单实还是多例 曾经面试的时候有面试官问 ...

  5. spring 或 springboot统一异常处理

    spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...

  6. 配置和修改springboot默认国际化文件

    SpringBoot默认国际化文件为:classpath:message.properties,如果放在其它文件夹中,则需要在application.properties配置属性spring.mess ...

  7. Springboot默认加载application.yml原理以及扩展

    Springboot默认加载application.yml原理以及扩展 SpringApplication.run(...)默认会加载classpath下的application.yml或applic ...

  8. 将SpringBoot默认使用的tomcat替换为undertow

    随着微服务的兴起,越来越多的互联网应用在选择web容器时使用更加轻量的undertow或者jetty.SpringBoot默认使用的容器是tomcat,如果想换成undertow容器,只需修改pom. ...

  9. SpringBoot默认日志的使用方法及常用配置

    SpringBoot默认采用slf4j+logback 的组合形式,但也提供对JUL.log4j2.Logback提供了默认配置. 我们使用IDEA的spring初始化创建一个springboot项目 ...

随机推荐

  1. FileOutputSream文件字节输出流

    1.FileOutputSream文件字节输出流:  输入--写出--使用:  输出--写入--存储: 写出写入是对硬盘而言: 其中,OutputStream为所有类型的字节输出流的超类: FileO ...

  2. Windows7 安装TensorFlow,python3.6

    TensorFlow 1.2.0新版本完美支持Python3.6,windows在cmd中输入pip install tensorflow就能下载应用最新tensorflow 只需在cmd中输入pip ...

  3. nodejs笔记之路由及util和url模块

    路由是URL到函数的映射:对于最简单的静态资源服务器,可以认为,所有URL的映射函数就是一个文件读取操作.对于动态资源,映射函数可能是一个数据库读取操作,也可能是进行一些数据的处理,等等. 如: /u ...

  4. C#匿名类型和动态解析减少定义传输类模板

    C#作为强类型语言,在序列化和反序列化(json)场景中对字符串解析常常需要定义强类型模板,造成编码上的繁琐.其实可以使用匿名类型和动态解析减少json序列化时候的数据模板定义: string a = ...

  5. iOS进阶之TCP代理鉴权过程

    这段时间接触了网络代理,而自己的任务是完成TCP和UDP的网络代理,所以在这里写些自己的理解吧. 这篇文章先介绍一下TCP代理的鉴权过程(采用的是用户名和密码鉴权),下一篇文章再介绍UDP代理的鉴权过 ...

  6. 湘潭邀请赛+蓝桥国赛总结暨ACM退役总结

    湘潭邀请赛已经过去三个星期,蓝桥也在上个星期结束,今天也是时候写一下总结了,这应该也是我的退役总结了~ --------------------------------湘潭邀请赛----------- ...

  7. c# 设计模式(一) 工厂模式

    源代码在github上面,需要的自己进行下载:https://github.com/yuzhoukamen/UnikmDesignPattern.git 工厂模式(Factory Pattern)是最 ...

  8. 1.2:Properties

    文章著作权归作者所有.转载请联系作者,并在文中注明出处,给出原文链接. 本系列原更新于作者的github博客,这里给出链接. 上一节我们了解了一个Shader的基本结构,这一节,我们从 Propert ...

  9. Cannot redeclare C() (previously declared in .

    在引入支付宝入口文件AopSdk.php的时候报错:Cannot redeclare C() (previously declared in D:\phpStudy\WWW\thinkphp\help ...

  10. semaphore demo !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

    import 'dart:async'; import 'package:semaphore/semaphore.dart'; import 'dart:io'; import 'dart:conve ...