Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of client handling for feign server discovering exception

Shulou Source: shulou.com Published: 2022-06-03 11:59:50 09月28日 Update

This article introduces the relevant knowledge of "the method of handling exceptions found by the feign server". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Preface

When using feign for remote method calls, if the remote server method has an exception, the client sometimes needs to catch and return the exception information to the front end, and if the exception is digested after the fuse is turned on, so, if you want to get the server exception, feign.hystrix.enable needs to be set to false, and when the fuse is not enabled, we also have several ways to get the exception information from the server. Let's sum up.

Try...catch method feign exception interceptor

Try...catch method

This approach is intuitive and best understood, but there will be a lot of try...catch code in the business layer, so it is not highly recommended.

Note: although the server-side method returns ResponseEntity, it will still throw a FeignException exception when an exception such as 4xxPower5xx occurs. For the service, the server-side exception of 5xx is thrown to the front end, which is not what we want to see.

Try {ResponseEntity body = productClient.add (name); if (body.getStatusCode (). Equals (HttpStatus.OK)) {return "test";} else {return body.getBody (). ToString ();}} catch (FeignException ex) {return ex.getMessage ();}

Feign exception interceptor

We recommend using this method to register a bean object, which will be triggered when an exception occurs in the feign call, and then we will handle the exception in a unified way and continue to throw the processed error message downstream.

/ * feign exception interceptor, which is used when an exception is thrown from feign. * / @ Configuration@Slf4jpublic class FeignClientErrorDecoder implements ErrorDecoder {@ Override public Exception decode (String methodKey, Response response) {logger.info ("feign client response:", response); String body = null; try {body = Util.toString (response.body (). AsReader ());} catch (IOException e) {logger.error ("feign.IOException", e);} if (response.status () > = 400 & & response.status ()

Tags: Methods services interceptors clients clients processing information content front-end objects more knowledge process or recommendation practical end-to-end intuitive learned and then Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MariaDB MySQL macOS Docker