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. Kindle:自动追更之发送邮件

    @echo off setlocal enabledelayedexpansion set from=Kindlekindle设置好信任的邮箱set pw=密码 set to=Kindle邮箱 cd ...

  2. Hadoop 安全模式safemode

    启动Hdfs 系统的时候,其中的一个阶段“”安全模式 发生阶段:NameNode启动中,已经读取了fsimage 并且生成了edits 文件,在等待dataNode 向nameNode 发送block ...

  3. Flask实战-留言板-使用Flask-DebugToolbar调试程序、Flask配置的两种组织形式

    使用Flask-DebugToolbar调试程序 扩展Flask-DebugToolbar提供了一系列调试功能,可以用来查看请求的SQL语句.配置选项.资源加载情况等信息.这些信息在开发时会非常有用. ...

  4. GO map

    map是一种无序的基于key-value的数据结构,Go语言中的map是引用类型,必须初始化才能使用. map定义 语法:map[KeyType]ValueType KeyType:表示键的类型. V ...

  5. Mysql查询创建和导入操作

    如何安装: https://www.cnblogs.com/bigbrotherer/p/7241845.html 登录: mysql -uroot -p 输入密码:xxxx 显示当前数据库: sho ...

  6. 外网访问内网MariaDB数据库

    外网访问本地MariaDB数据库 本地安装了MariaDB数据库,只能在局域网内访问,怎样从公网也能访问内网MariaDB数据库? 本文将介绍具体的实现步骤. 1. 准备工作 1.1 安装并启动Mar ...

  7. spider爬虫练习

    package com.jinzhi.spider; import java.io.BufferedReader;import java.io.IOException;import java.io.I ...

  8. redis的数据持久化策略

    redis提供了两种不同的持久化方法来将数据存储到硬盘里面.一种方法叫快照,它可以将存在于某一时刻的所有数据都写入硬盘里面.另一种方法叫只追加文件(AOF),它会在执行写命令时,将被执行的写命令复制到 ...

  9. 【mac微信小助手】WeChatPlugin使用教程!

    微信小助手 mac版集微信防撤回和微信多开等诸多功能于一身,可以有效的阻止朋友微信撤回消息,还能开启无手机验证登录,再也不用每次登录扫码验证啦,非常方便!   wechatplugin mac版安装教 ...

  10. UITextField只能输入数字NSCharacterSet实现

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementS ...