技术标签: spring cloud
Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求。
网关都是给接口做代理转发的,后端对应的都是REST API,返回数据格式都是JSON。如果不做处理,当发生异常时,Gateway默认给出的错误信息是页面,不方便前端进行异常处理。
需要对异常信息进行处理,返回JSON格式的数据给客户端。下面先看实现的代码,后面再跟大家讲下需要注意的地方。
自定义异常处理逻辑:
package com.cxytiandi.gateway.exception;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* 自定义异常处理
*
* <p>异常时用JSON代替HTML异常信息<p>
*
* @author yinjihuan
*
*/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
}
/**
* 获取异常属性
*/
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
int code = 500;
Throwable error = super.getError(request);
if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
code = 404;
}
return response(code, this.buildMessage(request, error));
}
/**
* 指定响应处理方法为JSON处理的方法
* @param errorAttributes
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
/**
* 根据code获取对应的HttpStatus
* @param errorAttributes
*/
@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
int statusCode = (int) errorAttributes.get("code");
return HttpStatus.valueOf(statusCode);
}
/**
* 构建异常信息
* @param request
* @param ex
* @return
*/
private String buildMessage(ServerRequest request, Throwable ex) {
StringBuilder message = new StringBuilder("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();
}
/**
* 构建返回的JSON数据格式
* @param status 状态码
* @param errorMessage 异常信息
* @return
*/
public static Map<String, Object> response(int status, String errorMessage) {
Map<String, Object> map = new HashMap<>();
map.put("code", status);
map.put("message", errorMessage);
map.put("data", null);
return map;
}
}
覆盖默认的配置:
package com.cxytiandi.gateway.exception;
import java.util.Collections;
import java.util.List;
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;
/**
* 覆盖默认的异常处理
*
* @author yinjihuan
*
*/
@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) {
JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
errorAttributes,
this.resourceProperties,
this.serverProperties.getError(),
this.applicationContext);
exceptionHandler.setViewResolvers(this.viewResolvers);
exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
return exceptionHandler;
}
}
在org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler中的getRoutingFunction()方法就是控制返回格式的,原代码如下:
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(
ErrorAttributes errorAttributes) {
return RouterFunctions.route(acceptsTextHtml(), this::renderErrorView)
.andRoute(RequestPredicates.all(), this::renderErrorResponse);
}
这边优先是用HTML来显示的,想用JSON的改下就可以了,如下:
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
原始的方法是通过status来获取对应的HttpStatus的,代码如下:
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
int statusCode = (int) errorAttributes.get("status");
return HttpStatus.valueOf(statusCode);
}
如果我们定义的格式中没有status字段的话,这么就会报错,找不到对应的响应码,要么返回数据格式中增加status子段,要么重写,我这边返回的是code,所以要重写,代码如下:
@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
int statusCode = (int) errorAttributes.get("code");
return HttpStatus.valueOf(statusCode);
}
文章浏览阅读3.6k次。“嘉兴制造”,全球最大手机ODM工厂探秘 在短短的几年时间,闻泰通讯公司从只有三十几个人的设计团队,“蝶变”成为小米、华为、联想等全球知名手机厂商合作伙伴,企业总产值超80亿元。如今,闻泰通讯不仅是南湖区信息产业的龙头企业,更是成为全球最大的手机ODM企业之一,为全球知名手机厂商提供产品定义、方案设计、生产制造、软件开发等服务。……以下是闻泰通讯宣传视频……▼▼闻泰通讯有别于其他设计公司与_odm厂
文章浏览阅读1.4w次,点赞2次,收藏17次。刚刚有看到一篇文章写的是COOLMOS管与常规MOS管的区别,这是一篇名为《初学者必备知识——功率场效应晶体管MOS管》里面有介绍很多MOS管知识,在这我就不说别的,我们来说说COOLMOS管,因为本公司-深圳市凯泰电子有限公司也有这样的MOS管,但是不叫COOLMOS管,我们的叫超结MOS管(Super Junction MOSFET Series)。下面我先介绍下COOLMOS管与常规MO_超结mos和coolmos区别
文章浏览阅读837次。一、下载 erlang-20.2.2-1.el7.centos.x86_64.rpm 并安装二、下载rabbit安装:rpm --import https://www.rabbitmq.com/rabbitmq-release-signing-key.asc; yum install rabbitmq-server-3.7.2-1.el7.noarch.rpm三、设置开机启动:chkcon_erlang-20.2.2-1.el7.centos.arch64.rpm
文章浏览阅读167次。转载:https://mochajs.cn_mocha api
文章浏览阅读948次。JVM结构.内存分配,垃圾回收,调优参数等._java jvm
文章浏览阅读8.1k次。IntelliJ IDEA和Postman,作为两款日常使用率非常高的软件,两者配合使用能够提高日常的开发效率。_springboot用什么软件编写
文章浏览阅读1.4k次。【天极网IT新闻频道】【Yesky新闻频道消息】 今日凌晨,苹果不仅正式发布了新一代操作系统iOS 9,还发布了一款应用移植工具Move to iOS。据悉,这款应用可以帮助用户将应用由Android迁移到iOS,同时这也是苹果开发的首款Android应用。据了解,Move to iOS是一款免费应用,只支持Android 4.0及更高的Android版本。苹果推出免费安卓应用移植工具Move t..._安卓开发的应用转换为苹果
文章浏览阅读1.8w次,点赞4次,收藏24次。介绍如何校准Linux服务器时间_linux时间校准
文章浏览阅读145次。Maven高级1.基础知识回顾:1.1Maven的核心依赖管理和一键构建(基础知识)1.2Maven仓库类型和仓库关系1.3Maven常见命令:1.4.maven生命周期2.Maven工程导入jar包坐标,必须考虑解决jar包冲突解决jar包冲突的方式一:解决jar包冲突的方式二:解决jar包冲突的方式三【推荐使用】:SSM框架不冲突的依赖包:3.Maven的拆分和聚合思想1.背景:2.工程、模块、项目的关系4.父子工程3种启动方式1.基础知识回顾:1.1Maven的核心依赖管理和一键构建(基础知识)
文章浏览阅读1.2k次。代码控制shader的自发光的开关mat.EnableKeyword("_EMISSION");//开 mat.DisableKeyword("_EMISSION");//关_unity shader enablekeyword
文章浏览阅读385次。Underscore.js是一个JavaScript实用库,提供了一整套函数式编程的实用功能,但是没有扩展任何JavaScript内置对象。弥补了部分jQuery没有实现的功能,同时又是Backbone.js必不可少的部分Underscore提供了100多个函数,包括常用的: map, filter, invoke — 当然还有更多专业的辅助函数,如:函数绑定, JavaScript模板功能,创建快速索引, 强类型相等测试Underscore是DocumentCloud的一个开源组件。.._unders js
文章浏览阅读4.8k次,点赞2次,收藏13次。R包【安装包】#指令下载R安装包install.packages("packge-name")#通过以下步骤安装点击右下方页面窗口中的“packages”--“install”进行安装,输入所要安装的R包名,默认从官网上下载#对于版本不合适的使用bioconductor安装if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")BiocManager::install_下载r语言中的数据集