@RestControllerAdvice使用

本文详细介绍了@RestControllerAdvice在Spring MVC中的应用,包括如何处理后端数据校验、未授权、自定义及普通异常,并展示了优化后的异常处理代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1.主要作用

2.判断异常的类型

3.实现


1.主要作用

@RestControllerAdvice主要用精简客户端返回异常,它可以捕获各种异常

2.判断异常的类型

1.后端数据校验异常

2.未授权异常

3.自定义异常

4.普通异常

3.实现

未优化前

import com.qing.emos.wx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@Slf4j
//@RestControllerAdvice可以捕获SpringMVC异常
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    ExceptionHandler用于全局捕获异常
    @ExceptionHandler(Exception.class)
    public String validExcepionHandler(Exception e){
        log.error("执行异常",e);
//        后端验证失败的异常,参数没传,或者传的不对
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        }
//        精简异常的内容,EmosException为自己定义异常
        else if(e instanceof EmosException){
            EmosException exception = (EmosException) e;
            return  exception.getMsg();
        }
//        未授权异常
        else if(e instanceof UnauthorizedException){
            return "你不具备相关权限";
        }
//       普通异常
        else {
            return "后端执行异常";
        }
    }
}

优化后

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值