服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot FeignClient 如何捕获业务异常信息

Spring Boot FeignClient 如何捕获业务异常信息

2021-09-19 11:30lucax2039 Java教程

这篇文章主要介绍了Spring Boot FeignClient 如何捕获业务异常信息的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Spring Boot FeignClient 捕获业务异常信息

因项目重构采用spring cloud,feign不可避免。目前spring cloud在国内还不是很成熟,所以踩坑是免不了的。最近处理全局异常的问题,搜了个遍也没找到合适的解决方案

1.全局异常处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import com.bossien.common.comm.entity.ResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * @Author: lixg
     * @Description: 系统异常捕获处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseDto errorExceptionHandler(Exception ex) {//APIResponse是项目中对外统一的出口封装,可以根据自身项目的需求做相应更改
        logger.error("捕获到 Exception 异常", ex);
        //异常日志入库
        return new ResponseDto(ResponseDto.RESPONSE_FAIL, "系统繁忙,请稍后再试");
    }
    /**
     * @Author: lixg
     * @Description: 自定义异常捕获处理
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)//BusinessException是自定义的一个异常
    public ResponseDto businessExceptionHandler(BusinessException ex) {
        logger.error("捕获到 BusinessException 异常: code=" + ex.getCode() + " , errorMessage=" + ex.getErrorMessage());
        return new ResponseDto(ex.getCode(), ex.getErrorMessage());
    }
}

2.请求参数解析handler

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import com.alibaba.fastjson.JSONObject;
import com.ocean.common.comm.entity.ResponseDto;
import com.ocean.common.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
 * @author lixg
 *
 * feign请求响应对象处理
 */
public class ResponseHandler {
    private final static Logger logger = LoggerFactory.getLogger(ResponseHandler.class);
    /**
     * 解析请求响应对象
     * @param responseDto
     * @param clazz
     * @return
     * @throws BusinessException
     */
    public static Object getResponseData(ResponseDto responseDto, Class clazz) throws BusinessException {
        if(EmptyUtil.isEmpty(responseDto)){
            throw new BusinessException(BusinessException.OBJECT_IS_NULL,"请求响应为空!");
        }
        if(ResponseDto.RESPONSE_SUCCESS.equals(responseDto.getCode())){
            try {
                String json = JSONObject.toJSONString(responseDto.getData());
                return JSONObject.parseObject(json, clazz);
            }catch (Exception e){
                logger.error("响应对象转换异常:"+clazz.getName(),e);
                throw new BusinessException(BusinessException.OBJECT_IS_NULL,"响应对象转换失败!");
            }
        }else{
            throw new BusinessException(responseDto.getCode(),responseDto.getMessage());
        }
    }
}

3.业务feign接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.bossien.usercenter.user.feign;
import com.bossien.common.comm.entity.ResponseDto;
import com.bossien.common.comm.util.PageModel;
import com.bossien.common.comm.constant.SearchEntity;
import com.bossien.common.core.exception.BusinessException;
import com.bossien.usercenter.user.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@FeignClient(value="bossien-usercenter-service",path = "/userFeign")
@Repository
public interface UserFeign {
    @RequestMapping(value = "getUserInfo",method = RequestMethod.GET)
    User getUserInfo(@RequestParam("userId") Long userId);
    @RequestMapping(value = "getUserInfoByTicket",method = RequestMethod.GET)
    ResponseDto getUserInfoByTicket(@RequestParam("ticket") String ticket) throws BusinessException;
 }

总结:

@controllerAdvice或者HandlerExceptionResolver是不能直接捕获到FeignException,所以需要在Feign层面拿到具体异常重新封装。最后总算把cloud service内部的异常安全(一样的错误码、一样的错误信息)送给了client!!

Feign调用异常处理

consumer服务调用Producer服务接口时,提示一下异常

no suitable HttpMessageConverter found for request type

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [com.xxx.pojo.Xxx] and content type [application/x-www-form-urlencoded]
 at org.springframework.cloud.openfeign.support.SpringEncoder.encode(SpringEncoder.java:143) ~[spring-cloud-openfeign-core-2.1.0.RELEASE.jar:2.1.0.RELEASE]
 at feign.ReflectiveFeign$BuildEncodedTemplateFromArgs.resolve(ReflectiveFeign.java:372) ~[feign-core-10.1.0.jar:na]
 at feign.ReflectiveFeign$BuildTemplateByResolvingArgs.create(ReflectiveFeign.java:224) ~[feign-core-10.1.0.jar:na]
 at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:74) ~[feign-core-10.1.0.jar:na]
 at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:106) ~[feign-hystrix-10.1.0.jar:na]
 at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) ~[hystrix-core-1.5.18.jar:1.5.18]
 at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298) ~[hystrix-core-1.5.18.jar:1.5.18]
 at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.Observable.unsafeSubscribe(Observable.java:10151) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.Observable.unsafeSubscribe(Observable.java:10151) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.Observable.unsafeSubscribe(Observable.java:10151) ~[rxjava-1.2.0.jar:1.2.0]
 at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94) ~[rxjava-1.2.0.jar:1.2.0]
 at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56) ~[hystrix-core-1.5.18.jar:1.5.18]
 at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47) ~[hystrix-core-1.5.18.jar:1.5.18]
 at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69) ~[hystrix-core-1.5.18.jar:1.5.18]
 at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55) ~[rxjava-1.2.0.jar:1.2.0]
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_221]
 at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_221]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_221]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_221]
 at java.lang.Thread.run(Thread.java:748) [na:1.8.0_221]

异常原因

如字面意思:

at org.springframework.cloud.openfeign.support.SpringEncoder.encode

缺少HttpMessageConverter 的编码器

解决方法

缺少那就加进去

将SpringFormEncoder加入到容器中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
/**
 * @author jianming
 * @create 2021-02-06-15:42
 */
@Configuration
public class FeignSupportConfig {
    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder();
    }
}

问题处理完成

Consumer的Feign使用

处理需要上述的编码器,还需在接口中指定ContentType

?
1
2
3
4
5
6
7
8
9
@Service
@FeignClient(value = "XXX-XXX")
public interface LoginService {
    /**
     * 指定contentType
     */
    @PostMapping(value = "/register", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public MsgUtils create(User user);
}

Producer正常编写即可!以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_36988277/article/details/90214665

延伸 · 阅读

精彩推荐
  • Java教程小米推送Java代码

    小米推送Java代码

    今天小编就为大家分享一篇关于小米推送Java代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    富贵稳中求8032021-07-12
  • Java教程Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中S...

    阿杜7472021-02-04
  • Java教程Java BufferWriter写文件写不进去或缺失数据的解决

    Java BufferWriter写文件写不进去或缺失数据的解决

    这篇文章主要介绍了Java BufferWriter写文件写不进去或缺失数据的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    这篇文章主要介绍了Java使用SAX解析xml的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程20个非常实用的Java程序代码片段

    20个非常实用的Java程序代码片段

    这篇文章主要为大家分享了20个非常实用的Java程序片段,对java开发项目有所帮助,感兴趣的小伙伴们可以参考一下 ...

    lijiao5352020-04-06
  • Java教程升级IDEA后Lombok不能使用的解决方法

    升级IDEA后Lombok不能使用的解决方法

    最近看到提示IDEA提示升级,寻思已经有好久没有升过级了。升级完毕重启之后,突然发现好多错误,本文就来介绍一下如何解决,感兴趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java实现抢红包功能

    Java实现抢红包功能

    这篇文章主要为大家详细介绍了Java实现抢红包功能,采用多线程模拟多人同时抢红包,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙...

    littleschemer13532021-05-16
  • Java教程xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下...

    Java教程网2942020-09-17