Spring 实战 7.3 处理异常

默认情况下,Spring会将自身的一些异常自动转换为合适的状态码,映射关系如下

Spring异常HTTP状态码
BindException400 - Bad Request
ConversionNotSupportedException500 - Internal Server Error
HttpMediaTypeNotAcceptableException406 - Not Acceptable
HttpMediaTypeNotSupportedException415 - Unsupported Media Type
HttpMessageNotReadableException400 - Bad Request
HttpMessageNotWritableException500 - Internal Server Error
HttpRequestMethodNotSupportedException405 - Method Not Allowed
MethodArgumentNotValidException400 - Bad Request
MissingServletRequestParameterException400 - Bad Request
MissingServletRequestPartException400 - Bad Request
NoSuchRequestHandlingMethodException404 - Not Found
TypeMismatchException400 - Bad Request

类似这种效果

我们可以自定义异常映射为特定的状态码

@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "data not exist")
public class NotExistException extends RuntimeException {
}
@RestController
public class IndexController {
    @RequestMapping("/test")
    @ResponseBody
    public String test(String param) {
        System.out.println("param:" + param);
        if (param == null) {
            throw new NotExistException();
        }
        return param;
    }
}

效果如图

处理当前controller中的异常

@RestController
public class IndexController {
    @RequestMapping("/test")
    @ResponseBody
    public String test(String param) {
        System.out.println("param:" + param);
        if (param == null) {
            throw new NotExistException();
        }
        return param;
    }
    @ExceptionHandler(NotExistException.class)
    public String handlerNotExistException() {
        return "123";
    }
}

再次调用效果如下,这里异常已经被ExceptionHandler捕获了


如果需要全局捕获需要引入新的解决方案:控制器通知(controller advice)。控制器通知是任意带有@ControllerAdvice注解的类

@RestControllerAdvice
public class ExceptionConfig {
    @ExceptionHandler(NotExistException.class)
    public String handlerNotExistException() {
        return "123";
    }
}

ExceptionConfig中的注解需要与Controller中的注解一致(@RestControllerAdvice对应controller中的@RestController、@ControllerAdvice对应controller中的@Controller)否则会不生效

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值