spring boot 2 统一异常处理

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上淘来的,以上是结合实际项目的应用,记录下来,方便以后查阅。

原文地址:https://www.cnblogs.com/lixyu/p/9593733.html

时间: 2024-08-30 08:51:05

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

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

摘自:https://www.cnblogs.com/greyzeng/p/11733327.html Practitioner 需要不断努力,才能毫不费力 基于Spring Boot的统一异常处理设计 基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支持RestControllerAdvice统一处理异常,在一个请求响应周期当中,如果Contro

基于spring boot的统一异常处理

一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我们认为制造一个异常 @GetMapping(value = "/girls") public List<Girl> girlList() throws Exception{ throw new Exception("错误"); } 使用浏览器访问http:/

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

本随笔记录使用Spring Boot统一处理异常. 本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14--20岁之间.小于14岁,提示"你可能在上初中":大于20岁,提示"呢可能在上大学". 第一步,创建枚举类ResultEnum,用来管理异常信息 package *;//自己定义 public enum ResultEnum { UNKONW_ERROR(-1, "未知错误"), SUCCESS(0, "成功")

spring 或 springboot统一异常处理

spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义异常处理,即在Controller中抛出自定义的异常时,客户端收到更友好的JSON格式的提示.而不是常见的报错页面. 二,场景描述:实现公用API,验证API key的逻辑,放在拦截器中判断(等同于在Controller中)并抛出异常,用户收到类似下图的提示: 其中,Http状态Code也能自由控制

Spring中的统一异常处理

在具体的SSM项目开发中,由于Controller层为处于请求处理的最顶层,再往上就是框架代码的.因此,肯定需要在Controller捕获所有异常,并且做适当处理,返回给前端一个友好的错误码. 不过,Controller一多,我们发现每个Controller里都有大量重复的.冗余的异常处理代码,很是啰嗦.能否将这些重复的部分抽取出来,这样保证Controller层更专注于业务逻辑的处理,同时能够使得异常的处理有一个统一的控制中心点. 全局异常处理1.1. HandlerExceptionReso

分享spring boot controller统一日志代码

最近项目需要做一个controller层的aop,主要解决下面问题: 1.controller日志统一打印输出json格式,兼容json和velocity . 2.项目异常处理 3.异常邮件发送 4.页面访问统计 主要思路使用aop实现,controller参数统一使用@RequestParam接收. controller @RequestMapping(name = "添加个人信息", value ="/addInfo", method = RequestMeth

Spring MVC自定义统一异常处理类,并且在控制台中输出错误日志

在使用SimpleMappingExceptionResolver实现统一异常处理后(参考Spring MVC的异常统一处理方法), 发现出现异常时,log4j无法在控制台输出错误日志.因此需要自定义一个继承至SimpleMappingExceptionResolver的 RrtongMappingExceptionResolver类,在RrtongMappingExceptionResolver中通过 log.error(ex.getMessage())的方式输出日志到控制台上.以下是具体的配

Spring中的统一异常处理方式

源自:https://segmentfault.com/a/1190000016236188 在具体的SSM项目开发中,由于Controller层为处于请求处理的最顶层,再往上就是框架代码的. 因此,肯定需要在Controller捕获所有异常,并且做适当处理,返回给前端一个友好的错误码. 不过,Controller一多,我们发现每个Controller里都有大量重复的.冗余的异常处理代码,很是啰嗦.能否将这些重复的部分抽取出来,这样保证Controller层更专注于业务逻辑的处理,同时能够使得异

Spring Boot入门——全局异常处理

1.后台处理异常 a.引入thymeleaf依赖 <!-- thymeleaf模板插件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> b.在application.properties文件中设置属性 #关闭thy