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

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

通过全局异常处理返回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;


@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"})

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5687682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存