springboot 默认异常处理
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 默认异常处理的更多相关文章
- java框架之SpringBoot(7)-异常处理
前言 在 SpringBoot 项目中,默认情况下,使用浏览器访问一个不存在的地址会返回如下错误页面: 而当客户端未非浏览器时,错误信息则会以 json 数据返回,如下: 会出现如上效果的原因是 Sp ...
- springboot 全局异常处理
springboot 全局异常处理 研究了半天springboot的全局异常处理,虽然还是需要再多整理一下,但是对于常见的404和500足以可以区分开,能够根据这两个异常分别处理 首先配置视图解析路径 ...
- Springboot的异常处理与自定义异常
园友们好,元旦很快就到来了,提前祝各位园友们元旦快乐,今天给大家分享一个工作中必用一个知识点,就是使用枚举构建自定义异常并应用于springboot的异常处理器.开始之前我先把这个案例的结构大致说明一 ...
- springboot默认创建的bean是单实还是多例
转:https://blog.csdn.net/q1512451239/article/details/53122687 springboot默认创建的bean是单实还是多例 曾经面试的时候有面试官问 ...
- spring 或 springboot统一异常处理
spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...
- 配置和修改springboot默认国际化文件
SpringBoot默认国际化文件为:classpath:message.properties,如果放在其它文件夹中,则需要在application.properties配置属性spring.mess ...
- Springboot默认加载application.yml原理以及扩展
Springboot默认加载application.yml原理以及扩展 SpringApplication.run(...)默认会加载classpath下的application.yml或applic ...
- 将SpringBoot默认使用的tomcat替换为undertow
随着微服务的兴起,越来越多的互联网应用在选择web容器时使用更加轻量的undertow或者jetty.SpringBoot默认使用的容器是tomcat,如果想换成undertow容器,只需修改pom. ...
- SpringBoot默认日志的使用方法及常用配置
SpringBoot默认采用slf4j+logback 的组合形式,但也提供对JUL.log4j2.Logback提供了默认配置. 我们使用IDEA的spring初始化创建一个springboot项目 ...
随机推荐
- get_class __class__ get_called_class 分析记录
首先看代码: class A { use T { T::say as aTsay; } public function say() { echo 'a__class__:' . __CLASS__ . ...
- selenium 定位密码软键盘
from selenium import webdriver import time driver = webdriver.Chrome() driver.maximize_window() driv ...
- zigbee端口的理解
在一个终端上,可以有多个端点endpoint,这个概念是很重要的. 一个节点可以有多个端点,0号endpoint是Zigbee device object(ZDO)用的一个端点,255号是用作广播.我 ...
- maven的两种打包插件 ,防止 将无用文件打入META_INF,找不到主类的问题
第三种 打依赖包 将依赖其他jar的包都打进去 <plugin> <artifactId>maven-assembly-plugin</artifactId> &l ...
- pthread_cond_wait虚假唤醒
pthread_cond_wait中的while()不仅仅在等待条件变量前检查条件cond_is_false是否成立,实际上在等待条件变量后也检查条件cond_is_false是否成立.在多线程等待的 ...
- 用vue脚手架创建bootstrap-vue项目
用vue脚手架创建bootstrap-vue项目 框架的地址:https://bootstrap-vue.js.org/docs/ 第一步 vue init webpack demo第二步 cd de ...
- Mask rcn nanchor部分理解
Anchors Mask 生成锚框本质与SSD一样中心点个数等于特征层像素数框体生成围绕中心点Bbox的坐标是要归一化到0~1之间的,都是相对于输入图片的大小.基本生成方式:H乘np.sqrt(anc ...
- hdu1172(枚举)
中文题,题意就不解释了. 思路:因为答案一定是四位数,所以只要枚举1000-9999,如果符合所有条件,那么保存一下答案,记录一下答案的个数,如果答案是唯一的,那么输出它,否则,就不确定. 代码如下: ...
- JS引擎的执行机制:探究EventLoop(含Macro Task和Micro Task)
在我看来理解好JS引擎的执行机制对于理解JS引擎至关重要,今天将要好好梳理下JS引擎的执行机制. 首先解释下题目中的名词:(阅读本文后你会对这些概念掌握了解) Event Loop:事件循环Micro ...
- Mac上超好用的计时器和秒表
秒表 https://joaomoreno.github.io/thyme/ 计时器 https://github.com/michaelvillar/timer-app 更新---这个更棒!有网页有 ...