spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestControllerAdvice

public class GatewayExceptionHandler {

    /*@ExceptionHandler(Exception.class)
public JsonResult handleBusinessException(HttpServletRequest request, Exception e) {
e.printStackTrace();
String code = ErrorCodeEnum.SYSTEM_ERROR_STRING.getCode();
String message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "Service Currently Unavailable";
return JsonResult.ErrorResponse(code, message);
}*/ @ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}
}

下面记录一下,spring cloud gateway项目中重写 DefaultErrorWebExceptionHandler 类,实现自定义异常处理

首先写一个类继承 DefaultErrorWebExceptionHandler 类,重写方法

public class RmcloudExceptionHandler extends DefaultErrorWebExceptionHandler {

    /**
* Create a new {@code DefaultErrorWebExceptionHandler} instance.
*
* @param errorAttributes the error attributes
* @param resourceProperties the resources configuration properties
* @param errorProperties the error configuration properties
* @param applicationContext the current application context
*/
public RmcloudExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
} /**
* 确定返回什么HttpStatus
*
* @param errorAttributes
* @return
*/
@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
//HttpStatus status = (HttpStatus) errorAttributes.get("status");
// return HttpStatus.INTERNAL_SERVER_ERROR == status ? HttpStatus.OK : status;
return HttpStatus.OK;
} /**
* 返回的错误信息json内容
*
* @param request
* @param includeStackTrace
* @return
*/
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Throwable error = this.getError(request); return JsonResult.responseReturnMap(RmcloudConstant.GATEWAY_ERRORCODE, this.buildMessage(request, error)); } private String buildMessage(Throwable t) {
return "未知错误!";
} private String buildMessage(ServerRequest request, Throwable ex) {
StringBuilder message = new StringBuilder("api-gateway Failed to handle request [");
message.append(request.methodName());
message.append(" ");
message.append(request.uri());
message.append("]");
if (ex != null) {
message.append(": ");
message.append(ex.getMessage());
}
return message.toString();
} private HttpStatus determineHttpStatus(Throwable error) {
return error instanceof ResponseStatusException ? ((ResponseStatusException) error).getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
} }

然后,配置自定义的ExceptionHandler


import com.vcredit.rmcloud.gateway.exception.RmcloudExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver; import java.util.Collections;
import java.util.List; /**
* webflux全局异常处理器配置配置
* 由于webflux的函数式编程方式中不能通过controllerAdvice只能通过每个RouterFunction中添加filter的方式实现异常处理,
* 这里通过注入一个自定义ErrorWebExceptionHandler来达到全局异常处理的目的
*
* @author lee
*/
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfiguration { private final ServerProperties serverProperties; private final ApplicationContext applicationContext; private final ResourceProperties resourceProperties; private final List<ViewResolver> viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer; public ErrorHandlerConfiguration(ServerProperties serverProperties,
ResourceProperties resourceProperties,
ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer,
ApplicationContext applicationContext) {
this.serverProperties = serverProperties;
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
this.viewResolvers = viewResolversProvider
.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
} @Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(
ErrorAttributes errorAttributes) {
RmcloudExceptionHandler exceptionHandler = new RmcloudExceptionHandler(
errorAttributes, this.resourceProperties,
this.serverProperties.getError(), this.applicationContext);
exceptionHandler.setViewResolvers(this.viewResolvers);
exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
return exceptionHandler;
}
}

JsonResult内容

@Data
@NoArgsConstructor
@AllArgsConstructor
public class JsonResult<T> { private static String successCode = ""; private String errorCode; private String msg; private T data; private Long timestamp; public static <T> JsonResult<T> successResponse(T data) {
return new JsonResult<>(successCode, "Success", data, System.currentTimeMillis());
} public static <T> JsonResult<T> errorResponse(String errorMessage) {
return new JsonResult<>(RmcloudConstant.GATEWAY_ERRORCODE, errorMessage, null, System.currentTimeMillis());
} public static <T> JsonResult<T> errorResponse(String status, String errorMessage) {
return new JsonResult<>(status, errorMessage, null, System.currentTimeMillis());
} public static Map<String, Object> responseReturnMap(String status, String errorMessage) {
Map<String, Object> map = new HashMap<>();
map.put("errorCode", status);
map.put("msg", errorMessage);
map.put("data", null);
return map;
}
}

最后感谢chenqian56131,主要代码是从他github上淘来的,以上是结合实际项目的应用,记录下来,方便以后查阅。

spring boot 2 统一异常处理的更多相关文章

  1. 基于Spring Boot的统一异常处理设计

    基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...

  2. spring boot配置统一异常处理

    基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...

  3. spring boot 中统一异常处理

    基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...

  4. 基于spring boot的统一异常处理

    一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我 ...

  5. Spring Boot实践——统一异常处理

    注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...

  6. Spring Boot学习——统一异常处理

    本随笔记录使用Spring Boot统一处理异常. 本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间.小于14岁,提示“你可能在上初中”:大于20岁,提示“呢可能在上大学” ...

  7. 【Spring Boot】Spring Boot之统一异常处理

    一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...

  8. Spring Boot API 统一返回格式封装

    今天给大家带来的是Spring Boot API 统一返回格式封装,我们在做项目的时候API 接口返回是需要统一格式的,只有这样前端的同学才可对接口返回的数据做统一处理,也可以使前后端分离 模式的开发 ...

  9. spring 或 springboot统一异常处理

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

随机推荐

  1. Jboss安装配置以及相关的问题

    下载地址:(目前最新版本是jboss-as-7.1.1.Final) http://download.jboss.org/jbossas/7.1/jboss-as-7.1.1.Final/jboss- ...

  2. Python脚本之Lrc歌词去时间轴转Txt文件,附带酷狗音乐APP关联已有krc歌词

    一.Lrc歌词去时间轴转Txt文件 环境:Python2.7.x, Mac(Windows需装cygwin环境,当然你也可以自己改代码,Python新手,勿喷) # -*- coding: UTF-8 ...

  3. 上传本地代码到gitHub过程详解

    1.注册Github账号 2.创建自己的GitHub仓库 3.创建自己的Repository(项目的名字等) 4.复制创建仓库的地址到Git命令窗口并执行命令行(Git clone 仓库的复制地址) ...

  4. 20175236 JAVA MyCP(课下作业)

    具体描述: 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: java MyCP -tx XXX1.txt XXX2.bin 用来把文本文件(内容 ...

  5. JSONObject 转List 强制类型转换错误

    JSONArray arr=(JSONArray)map.getOrDefault("data","");List<DHD> data=JSONOb ...

  6. Go语言操作MySQL数据库

    Go语言操作MySQL数据库 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用 ...

  7. IDEA注册码分享

    IntelliJ IDEA IDEA 2018 激活注册码分享鼠标连续 三下左键点击 选中,再Ctrl+C 即可复制. CSDN在末尾会带上博客的说明,请删除后,复制到 IDEA中激活. 注册码激活: ...

  8. winform里面的Form1.Designer.cs

    Program.cs是程序入口,也就是Main函数.Form1.cs是实现功能的代码,包括你的自定义方法和事件.Form1.Designer.cs是你的画面的设计代码,一般由系统自动生成,也可以手动修 ...

  9. NoSuchMethodError解决方法

    下面演示下如何在啥都不知道的情况下遇到该错误的解决思路: 随便找一个错误示例: Caused by: java.lang.NoSuchMethodError: org.eclipse.jdt.inte ...

  10. layer.open参数;layer.open关闭事件;layer.open关闭刷新;layer.open获取子页的值;layer.open调用子页面的方法

    父页面 function layerOpen() { layer.open({ type: 2, shade: [0], title: "验收申请", area: ['1024px ...