通过全局异常处理返回openfeign接口调用结果

没有添加全局异常处理时,当Controller的方法直接抛出异常时,openfeign会收到500错误,导致无法进行正常的处理。通过定义全局异常处理,将异常情况,通过预定义的错误码进行返回,以便调用端能够正常处理。

1. 定义全局异常类

package com.demo.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * author:
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
        return AjaxResult.error(e.getMessage());
    }

//    @ExceptionHandler(BusinessException.class)
//    @ResponseBody
//    public Result handleException(BusinessException e, HttpServletRequest request) {
//        logger.warn("请求url:[{}]出错", request.getRequestURL(), e);
//        return ResultUtils.error(e.getCode(),e.getMessage());
//    }
}

2. 添加该类后,如果@ControllerAdvice不生效,需要确保能够扫描到,也就是需要放在启动类所在包之下。或者添加扫描路径,比如:

@SpringBootApplication(scanBasePackages = {"com.xxx"})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值