SpringBootFeignClient如何捕获业务异常信息
Spring Boot FeignClient 捕获业务异常信息
因项⽬重构采⽤spring cloud,feign不可避免。⽬前spring cloud在国内还不是很成熟,所以踩坑是免不了的。最近处理全局异常的问题,搜了个遍也没到合适的解决⽅案
1.全局异常处理
import ity.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 = Logger(GlobalExceptionHandler.class);
/**
* @Author: lixg
* @Description: 系统异常捕获处理
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ResponseDto errorExceptionHandler(Exception ex) {//APIResponse是项⽬中对外统⼀的出⼝封装,可以根据⾃⾝项⽬的需求做相应更改
<("捕获到 Exception 异常", ex);
//异常⽇志⼊库
return new ResponseDto(ResponseDto.RESPONSE_FAIL, "系统繁忙,请稍后再试");
}
/**
* @Author: lixg
spring framework* @Description: ⾃定义异常捕获处理
*/
@ResponseBody
@ExceptionHandler(value = BusinessException.class)//BusinessException是⾃定义的⼀个异常
public ResponseDto businessExceptionHandler(BusinessException ex) {
<("捕获到 BusinessException 异常: code=" + ex.getCode() + " , errorMessage=" + ex.getErrorMessage());
return new Code(), ex.getErrorMessage());
}
}
2.请求参数解析handler
import com.alibaba.fastjson.JSONObject;
ity.ResponseDto;
ption.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/***
* @author lixg
*
* feign请求响应对象处理
*/
public class ResponseHandler {
private final static Logger logger = Logger(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.Code())){
try {
String json = Data());
return JSONObject.parseObject(json, clazz);
}catch (Exception e){
<("响应对象转换异常:"+Name(),e);
throw new BusinessException(BusinessException.OBJECT_IS_NULL,"响应对象转换失败!");
}
}else{
throw new Code(),Message());
}
}
}
3.业务feign接⼝
package com.bossien.usercenter.user.feign;
import ity.ResponseDto;
import com.bossienmonm.util.PageModel;
import stant.SearchEntity;
import xception.BusinessException;
import com.bossien.ity.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
at feign.solve(ReflectiveFeign.java:372) ~[feign-core-10.1.0.jar:na]
at feign.ate(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 comflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) ~[hystrix-core-1.5.18.jar:1.5.18]
at comflix.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 comflix.urrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56) ~[hystrix-core-1.5.18.jar:1.5.18]
at comflix.urrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47) ~[hystrix-core-1.5.18.jar:1.5.18]
at comflix.urrency.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 urrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_221]
at urrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_221]
at urrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_221]
at urrent.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.de
缺少HttpMessageConverter 的编码器
解决⽅法
缺少那就加进去
将SpringFormEncoder加⼊到容器中
dec.Encoder;
import feign.form.spring.SpringFormEncoder;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Primary;
import t.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
@Service
@FeignClient(value = "XXX-XXX")
public interface LoginService {
/**
* 指定contentType
*/
@PostMapping(value = "/register", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public MsgUtils create(User user);
}
Producer正常编写即可!以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论