一、页面的形式返回

  直接在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. 蚂蚁风险大脑亮相ATEC城市峰会:为数字经济时代做好“安全守护”

    2019年1月4日,以“数字金融新原力(The New Force of Digital Finance)”为主题的蚂蚁金服ATEC城市峰会在上海隆重举行.大会聚焦金融数字化转型,分享新技术的发展趋势 ...

  2. CSS之垂直水平居中方法

    //居中方法1 position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 346px; height ...

  3. 接口测试工具Jmeter

    一.安装Jmeter 1.安装JDK ①下载jdk,到官网下载jdk,地址:http://jmeter.apache.org/download_jmeter.cgi ② 安装jdk(Oracle官网下 ...

  4. Confluence 6 超过当前许可证期限进行升级

    这个页面将会对你在进行 Confluence 升级的时候超过了当前许可证的期限进行升级的情况. 许可证警告 在升级的过程中,你将会在 Confluence 的应用程序日志(log file)中看到类似 ...

  5. 华为交换机VRP系统命令试图

  6. 深入了解UML类图

    深入浅出UML类图 在UML 2.0的13种图形中,类图是使用频率最高的UML图之一.Martin Fowler在其著作<UML Distilled: A Brief Guide to the ...

  7. 根据cid获取哔哩哔哩弹幕

    def biliget(cid): headers = { "Accept": "*/*", "Accept-Language": &quo ...

  8. javascript高级程序设计第3版——第8章 BOM(浏览器对象模型)

    第八章,浏览器对象模型 主要介绍了window的几个对象以及框架,窗口的关系,各个浏览器对象的属性以及方法:

  9. react component onClick 函数带参数

    <div onClick={this.toggleTip(true)}></div> toggleTip = shouldShowTip => () => { th ...

  10. springBoot 随笔(一)

    服务化的世界,越来越多应用拆分为微服务,有些为了业务而拆,也有为了技术而拆,也有什么都不知道就瞎拆的,反正就是要微服务. 以下为一个认识springBoot的简单过程 1/eclipse 新建 mav ...