当前位置: 首页 > 知识库问答 >
问题:

Spring Cloud Gateway全局异常处理和自定义错误响应

宋琛
2023-03-14

我有一个自定义过滤器,它在使用Spring Cloud Gateway调用实际API之前对每个请求进行身份验证。Spring Cloud中有没有像Spring提供@ControllerAdvision那样集中处理异常的方法?我希望全局处理异常,并从网关返回自定义错误响应。

共有1个答案

金宣
2023-03-14

一旦从身份验证筛选器引发异常,就可以通过重写DefaultErrorAttributes类来自定义错误响应。

@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes {


    private static final Logger logger = LoggerFactory.getLogger(GlobalErrorAttributes.class);

    public GlobalErrorAttributes() {
    }

    public GlobalErrorAttributes(boolean includeException) {
        super(includeException);
    }

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request,
                                                  boolean includeStackTrace) {
        Throwable error = this.getError(request);
        logger.error("Error occured", error);
        MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
                .from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class);
        HttpStatus errorStatus = findHttpStatus(error, responseStatusAnnotation);
        logger.info("errorStatus: {}", errorStatus);
        Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);
        String errorCode = getErrorCode(map, errorStatus);
        map.remove("timestamp");
        map.remove("path");
        map.remove("error");
        map.remove("requestId");
        map.put("errorCode", errorCode);
        return map;
    }

    private HttpStatus findHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) {
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getStatus();
        }
        return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(INTERNAL_SERVER_ERROR);
    }

    private String getErrorCode(Map<String, Object> map, HttpStatus errorStatus) {
        String errorCode;
        switch (errorStatus) {
            case UNAUTHORIZED:
                errorCode = "401 UnAuthorized";
                break;
            case NOT_FOUND:
                logger.error("The url:{} is not found", map.get("path"));
                errorCode = "404 Not Found";
                map.put(MESSAGE, "NOT FOUND");
                break;
            case METHOD_NOT_ALLOWED:
                logger.error("Invalid HTTP Method type for the url: {}", map.get("path"));
                errorCode = "405 Method Not Allowed";
                break;
            default:
                logger.error("Unexpected error happened");
                logger.error("errorstatus is : {}", errorStatus);
                errorCode = "500 Internal Server Error";
                map.put(MESSAGE, "Unexpected Error");
        }
        return errorCode;
    }
}

输出如下所示:

java prettyprint-override">{
   "status": 401,
   "message": "Invalid Access Token",
   "error_code": "401 UnAuthorized"
}
 类似资料:
  • 本文向大家介绍Springboot之自定义全局异常处理的实现,包括了Springboot之自定义全局异常处理的实现的使用技巧和注意事项,需要的朋友参考一下 前言: 在实际的应用开发中,很多时候往往因为一些不可控的因素导致程序出现一些错误,这个时候就要及时把异常信息反馈给客户端,便于客户端能够及时地进行处理,而针对代码导致的异常,我们一般有两种处理方式,一种是throws直接抛出,一种是使用try.

  • 统一错误处理 文档:https://eggjs.org/zh-cn/tutorials/restful.html 自定义一个异常基类 // app / exceptions / http_exceptions.js class HttpExceptions extends Error { constructor(msg='服务器异常', code=1, httpCode=400) {

  • 本文向大家介绍laravel框架 api自定义全局异常处理方法,包括了laravel框架 api自定义全局异常处理方法的使用技巧和注意事项,需要的朋友参考一下 api返回实现 api返回信息 1,添加异常类 2,修改laravel异常类u。。。 考虑开发配置时 以上这篇laravel框架 api自定义全局异常处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • Middleware: 全局异常处理 我们在岩浆的实例其实已经注意到了,compose 的连接方式,让我们有能力精确控制异常。 Koa中间件最终行为强依赖注册顺序,比如我们这里要引入的异常处理,必须在业务逻辑中间件前注册,才能捕获后续中间件中未捕获异常,回想一下我们的调度器实现的异常传递流程。 <?php class ExceptionHandler implements Middleware

  • 我为运行时可能发生的各种错误创建了多个自定义异常。为此,我使用@ControllerAdvice注释和全局错误处理程序(如下所述:Spring Boot 异常处理。我还在数据库级别实现了约束(如果这很重要,它是一个SQL Server数据库),并且我有一个表,该表具有插入数据时可能引发的两个不同约束。 我现在想做的是在Spring Boot中为数据库级别的每个约束实现自定义异常,这样我就可以向用户

  • 问题内容: 有没有一种方法可以添加一个全局包罗万象的错误处理程序,可以在其中将响应更改为通用JSON响应? 我无法使用该信号,因为它不允许修改响应(http://flask.pocoo.org/docs/0.10/signals/)。 相反,所有信号处理程序均以未定义的顺序执行,并且不修改任何数据。 我宁愿不要包装该函数,因为感觉就像是内部API。我想我正在寻找类似的东西: 请注意,不会接受任何参