Springboot项目全局异常处理

创建全局异常处理类:GlobalExceptionHandler

添加注解

@RestController
@ControllerAdvice
@Slf4j

import com.wallet.base.response.Result;
import com.wallet.base.response.ResultCode;
import com.wallet.base.response.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
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 org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;

/**
 * 全局异常处理
 *
 * @author andyhoop
 * @version create
 * @since 2023-02-09
 */
@Slf4j
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Throwable.class)
	@ResponseBody
	public Result customExceptionHandler(@NotNull Throwable e) throws Throwable {
		if (e instanceof CustomException) {
			return Result.FAIL(((CustomException) e).getResultCode());
		} else if (e.getCause() instanceof CustomException) {
			CustomException ex = (CustomException) e.getCause();
			return Result.FAIL(ex.getResultCode());
		}else if (e instanceof MethodArgumentNotValidException){
			String message = ((MethodArgumentNotValidException)e).getBindingResult().getFieldError().getDefaultMessage();
			return Result.FAIL(ResultCode.PARAM_MISS.getCode(),message);
		}
		if (e instanceof BindException) {
			log.error("GlobalExceptionHandler: {}", e.getMessage());
		} else {
			log.error("GlobalExceptionHandler", e);
		}
		throw e;
	}

}

可以捕获自定义异常,只需要在if else判断中添加判断,之后捕获异常,处理自己的业务逻辑。

注意::由于我的项目是一个微服务项目,这个GlobalExceptionHandler 类我定义在common服务中,之后每个服务需要单独配置,配置方式:只需要在项目中创建一个如下配置类

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 自动配置base beans
 *
 * @author andyhoop
 * @version create
 * @since 2023-02-09
 */
@Configuration
@ComponentScan(basePackageClasses = {com.wallet.base.interceptor.GlobalExceptionHandler.class})
public class BaseModuleConfig {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值