一、页面的形式返回

  直接在resources的目录下创建public/error的路径,然后创建5xx.html或者4xx.html文件,如果出错就会自动跳转的相应的页面。

二、cotroller的形式返回错误的处理

    1.自定义错误处理类

    

package com.kiyozawa.manager.error;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map; /**
* 自定义错误处理
*/
public class MyErrorController extends BasicErrorController { public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorProperties, errorViewResolvers);
} // {
// "timestamp": "2019-03-02 13:19:46.066",
// x "status": 500,
// x"error": "Internal Server Error",
// x "exception": "java.lang.IllegalArgumentException",
// "message": "编号不可为空",
// x "path": "/manager/products"
// } @Override
protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
//去除返回值中不必要的信息
attrs.remove("timestamp");
attrs.remove("status");
attrs.remove("error");
attrs.remove("exception");
attrs.remove("path");
//通过信息获取errorCode的值,最终获取errorEnum类的信息
String errorCode = (String) attrs.get("message");
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
//ErrorEnum类的信息存入attrs中返回给前端
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
return attrs;
}
}

把错误处理类自动配置到Springboot中

package com.kiyozawa.manager.error;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorViewResolver;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.List; @Configuration
public class ErrorConfiguration {
@Bean
public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
return new MyErrorController(errorAttributes, serverProperties.getError(),
errorViewResolversProvider.getIfAvailable());
}
}

自定义错误类型

package com.kiyozawa.manager.error;

public enum ErrorEnum {
ID_NoT_NULL("F001","编码不为空",false),
UNKOWN("000","位置异常",false);
private String code;
private String message;
private boolean canRetry;
ErrorEnum(String code,String message,boolean canRetry){
this.code=code;
this.message=message;
this.canRetry=canRetry;
}
public static ErrorEnum getByCode(String code){
for (ErrorEnum errorEnum:ErrorEnum.values()){
if(errorEnum.code.equals(code)){
return errorEnum;
}
}
return UNKOWN; } public String getCode() {
return code;
} public String getMessage() {
return message;
} public boolean isCanRetry() {
return canRetry;
}
}

另外的一种方式见下:

package com.kiyozawa.manager.error;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap;
import java.util.Map; /**
* 统一错误处理
*/
//路径为controller类的路径
@ControllerAdvice(basePackages = {"com.kiyozawa.manager.controller"})
public class ErrorControllerAdvice {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity handleException(Exception e){
Map<String, Object> attrs = new HashMap();
String errorCode = e.getMessage();
ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
attrs.put("message",errorEnum.getMessage());
attrs.put("code",errorEnum.getCode());
attrs.put("canRetry",errorEnum.isCanRetry());
attrs.put("type","advice");
// Assert.isNull(attrs,"advice");
return new ResponseEntity(attrs, HttpStatus.INTERNAL_SERVER_ERROR);
} }

  

Springboot 的错误处理功能的实现的更多相关文章

  1. sql 的错误处理功能很弱

    --下面演示了SQL错误处理的脆弱性--邹建 --演示1--测试的存储过程1create proc p1asprint 12/0if @@error<>0print '发生错误1' sel ...

  2. Atitit php java python nodejs错误日志功能的比较

    Atitit php  java  python  nodejs错误日志功能的比较 1.1. Php方案 自带 1 1.2. Java解决方案 SLF4J 1 1.3. Python解决方案 自带lo ...

  3. SpringBoot自定义错误信息,SpringBoot适配Ajax请求

    SpringBoot自定义错误信息,SpringBoot自定义异常处理类, SpringBoot异常结果处理适配页面及Ajax请求, SpringBoot适配Ajax请求 ============== ...

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

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

  5. springboot自定义错误页面

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

  6. 【链接】SpringBoot启动错误

    [错误解决]SpringBoot启动错误 https://blog.csdn.net/Small_Mouse0/article/details/78551900

  7. SpringBoot的注解注入功能移植到.Net平台(开源)

    *:first-child { margin-top: 0 !important; } .markdown-body>*:last-child { margin-bottom: 0 !impor ...

  8. SpringBoot简单实现登录功能

    登陆 开发期间模板引擎页面修改以后,要实时生效 1).禁用模板引擎的缓存 # 禁用缓存 spring.thymeleaf.cache=false 2).页面修改完成以后ctrl+f9:重新编译: 登陆 ...

  9. SpringBoot 整合Mail发送功能问题与解决

    SpringBootLean 是对springboot学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.oschina.n ...

随机推荐

  1. vivo 1805的usb调试模式在哪里,开启vivo 1805usb调试模式的流程

    经常我们使用安卓手机通过数据线连接上PC的时候,如果手机没有开启usb调试模式,PC则没办法成功识别我们的手机,部分软件也没办法正常使用,此情况我们需要找方法将手机的usb调试模式打开,下面我们讲解v ...

  2. lua --- 表操作

    c api 参考手册:http://www.leeon.me/a/lua-c-api-manual // LuaTest.cpp : 定义控制台应用程序的入口点. // #include " ...

  3. power shell 脚本了解

    1. https://www.cnblogs.com/xianglongsdu/p/5832984.html 2.https://www.cnblogs.com/lsdb/p/9531338.html ...

  4. 如何成为F1车手?

    sorry,玩了几天的GT sport才发现赛车有多难,理论的最佳走线是存在的,但是真实的赛道实在是千变万化,弯道形状角度.高低差.F1还有温度和风速,甚至是路面上的一个碎石都会极大地影响你的成绩.赛 ...

  5. Python自学:第三章 使用方法pop()删除元素

    motorcycle = ["honda", "yamaha", "suzuki"] last_owned = motorcycle.pop ...

  6. 【JAVA】servlet执行流程

    servlet执行流程 客户端发出http请求,web服务器将请求转发到servlet容器,servlet容器解析url并根据web.xml找到相对应的servlet,并将request.respon ...

  7. 322. Coin Change零钱兑换

    网址:https://leetcode.com/problems/coin-change/ 典型的动态规划问题,类比背包问题,这就是完全背包问题 问题的阶段:对数值 i 凑硬币 问题的状态:对数值 i ...

  8. react - next.js 设置body style

    因为next.js可以用pages文件夹中的js文件进行route,所以不需要public文件夹和html,因此没有body tag. body自带8px的maigin,我想要给整个页面设置背景颜色, ...

  9. C++标准模板库(STL)之String

    1.String的常用用法 在C语言中,使用字符数组char str[]来存字符串,字符数组操作比较麻烦,而且容易有'\0'的问题,C++在STL中加入string类型,对字符串常用的需求功能进行封装 ...

  10. centos7与centos6命令区别

    CentOS 7 vs CentOS 6的不同    (1)桌面系统[CentOS6] GNOME 2.x[CentOS7] GNOME 3.x(GNOME Shell) (2)文件系统[CentOS ...