当前位置:网站首页>Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
2022-08-02 01:01:00 【m0_67392409】
Generally, when we use feign to call the interface, if the service provider has an exception, the caller will generally display
feign.FeignException$BadRequest: status 400 readingRegardless of the downtime of the server, the corresponding information will be thrown when there is an exception, but the caller cannot obtain it in general.
Through testing, we found that if you print the log, you can see itThe log thrown by the service provider, but the caller cannot capture it, will only report a 400 exception.
So if we want to pass exceptions, we can have two ways, but most of them need to be adjusted by the caller.
First, fallbackFactory
FallbackFactory is similar to the standard fuse downgrade, which can bring all the exception information, but we need to convert the exception, and the regular exception still cannot get the body part.
So here we use FeignException to force the transfer, and the problem is solved.
Look, we can get the custom error thrown by the server.
At this time, you can convert the json to bean.
Reference:
Server and Client Common
@FeignClient(value = "sq-service", path = "/service",url = "http://localhost:9980", fallbackFactory = TestFactory.class)public interface TestApi {@PostMapping("/test")String test();}@Componentpublic class TestFactory implements FallbackFactory {@Overridepublic TestApi create(final Throwable throwable) {FeignException ex = (FeignException) throwable;JSONObject jsonObject = JSONObject.parseObject(ex.contentUTF8());return new TestApi() {@Overridepublic String test() {return jsonObject.getString("message");}};}} Attention!If the client wants to fuse and downgrade, it must be configured in the yaml file:
Client:
feign:hystrix:enabled: trueOtherwise cannot enter fallbackFactory
Second, once and for all, global configuration
I solve it directly with a config file!
Compared with fallbackFactory, there is no need for common code, no need to fuse and downgrade, and the server does not need to make any changes, only the client configuration is required.If you can't change the server, try not to move, otherwise, you really want to diss.
Client
@Configurationpublic class FeignErrorDecoder implements ErrorDecoder {@Overridepublic Exception decode(final String methodKey, final Response response) {try {String message = Util.toString(response.body().asReader());try {JSONObject jsonObject = JSONObject.parseObject(message);// Wrap it into your own custom exception, here it is recommended to change it according to your own codereturn new MyException(jsonObject.getString("message"), jsonObject.getInteger("code"));} catch (JSONException e) {e.printStackTrace();}} catch (IOException ignored) {}return decode(methodKey, response);}}
As you can see, this method can directly feedback to the caller,In other words, front-end calls can be directly displayed on the web page.It can be said that it is very direct to tell you that it is abnormal.
Feign's exception delivery is as simple as that. Generally speaking, projects have their own custom exception global classes for reference only.
Global processing is strongly recommended!!!
Let me introduce myself first. The editor graduated from Shanghai Jiaotong University in 2013. I worked in a small company and went to big factories such as Huawei and OPPO. I joined Alibaba in 2018, until now.I know that most junior and intermediate java engineers want to upgrade their skills, they often need to explore their own growth or sign up to study, but for training institutions, the tuition fee is nearly 10,000 yuan, which is really stressful.Self-learning that is not systematic is very inefficient and lengthy, and it is easy to hit the ceiling and the technology stops.Therefore, I collected a "full set of learning materials for java development" for everyone. The original intention is also very simple. I hope to help friends who want to learn by themselves but don't know where to start, and at the same time reduce everyone's burden.Add the business card below to get a full set of learning materials
边栏推荐
猜你喜欢

Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?

c语言字符和字符串函数总结(二)

dbeaver连接MySQL数据库及错误Connection refusedconnect处理

uni-app project summary

unity2D横版游戏教程5-UI

html+css+php+mysql实现注册+登录+修改密码(附完整代码)

IDEA如何运行web程序

nodeJs--mime module

Kubernetes — Flannel

from origin ‘null‘ has been blocked by CORS policy Cross origin requests are only supported for
随机推荐
go笔记记录——channel
Interview: Briefly describe a project you are involved in
百度、百图生科 | HelixFold-Single: 使用蛋白质语言模型作为替代进行无MSA蛋白质结构预测
DCM 中间件家族迎来新成员
Constructor, this keyword, method overloading, local variables and member variables
These 4 computer notepad software, you have to try
swing的Jlist列表滚动条以及增加元素的问题
ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)
Mapped Statements collection does not contain value for的解决方法
ImportError cannot import name ‘Mapping‘ from ‘collections‘
渗透测试与攻防对抗——渗透测试基础
H5页面打开微信小程序
flask获取post请求参数
管理基础知识15
PHP to read data from TXT file
攻防世界-web-Training-WWW-Robots
交返是做日内交易的必要条件
抖音数据接口API-获取用户主页信息-监控直播开启
期货开户手续费加一分是主流
Don't concatenate strings with jOOQ