spring Cloud 全局异常捕获

 通过@RestControllerAdvice来处理。


@RestControllerAdvice
public class GlobalExceptionAdvice {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    @ExceptionHandler(value = Exception.class)
    public ApiResult<String> handlerAdException(HttpServletRequest request, Exception ex) {
        ApiResult<String> response = new ApiResult<>();
        //返回部分异常
        response.setCodeToError(ex.getMessage());
        //输出完整异常
        logger.error("=========",ex);
        return response;
    }
}

ApiResult 是我自己包装的返回结果
public class ApiResult<T> {
	public static final String FAIL_CODE = "0";
	public static final String SUC_CODE = "1";
	public static final String ERROR_CODE = "2";
	public static final String SUC_MESSAGE = "Operate successfully";
	public static final String FAIL_MESSAGE = "Operation failure";
	public static final String ERROR_MESSAGE = "System Error";
	public static final String NOACCESS_MESSAGE = "No permission to access this page.";

	private String code = FAIL_CODE;
	private String message = FAIL_MESSAGE;
	private T data;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setCode(String code, String message) {
		this.code = code;
		this.message = message;
	}

	public void setCodeToSuccessed() {
		this.code = SUC_CODE;
		this.message = SUC_MESSAGE;
	}
	public void setCodeToSuccessed(T data) {
		this.data = data;
		this.code = SUC_CODE;
		this.message = SUC_MESSAGE;
	}
    
	public void setCodeToError(String message) {
		this.code = ERROR_CODE;
		this.message = message;
	}
	
	public void setCodeToError() {
		this.code = ERROR_CODE;
		this.message = ERROR_MESSAGE;
	}

	public void setCodeToFail(String message) {
		this.code = ERROR_CODE;
		this.message = message;
	}

	public void setCodeToFail() {
		this.code = FAIL_CODE;
		this.message = FAIL_MESSAGE;
	}
	
	public void setCodeByNoAccess() {
		this.code = FAIL_CODE;
		this.message = NOACCESS_MESSAGE;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public boolean isSuccess() {
		return SUC_CODE.equals(code);
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}
	
	
	
}

如果你需要捕获参数:

package com.leadtrans.report.advice;

import com.alibaba.fastjson.JSON;
import com.leadtrans.report.model.base.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author: Tyler
 * @createDate: 2021/12/24
 */


@RestControllerAdvice
public class GlobalExceptionAdvice implements RequestBodyAdvice {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
//        RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);
//        logger.info("请求地址====>{}", StringUtils.arrayToDelimitedString(requestMapping.value(), ","));
        logger.info("请求地址====>{}",parameter.getMethod().toString());
        logger.info("请求参数====>{}", JSON.toJSONString(body));
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        RequestMapping requestMapping = parameter.getMethodAnnotation(RequestMapping.class);
        logger.info("请求地址====>{}", StringUtils.arrayToDelimitedString(requestMapping.value(), ","));
        return body;
    }

    @ExceptionHandler(value = Exception.class)
    public ApiResponse<String> handlerAdException(HttpServletRequest request, Exception ex) {
        //输出完整异常
        logger.error("=========",ex);
        return new ApiResponse().Fail(ex.getMessage());
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值