@ControllerAdvice 处理400全局异常

错误请求导致400:http://localhost:8080/ex

异常提示如下:

java.lang.IllegalStateException: Could not resolve parameter [1] in public com.example.springbootexh.common.rest.entity.RestResult<java.lang.String> 
com.example.springbootexh.handle.GlobalExceptionHandler.requestNotReadable(javax.servlet.http.HttpServletRequest,
org.springframework.http.converter.HttpMessageNotReadableException): No suitable resolver

异常返回:

我的代码:

@RestController
@RequestMapping("/ex")
public class ExceptionController {

    /**
     * url: http:localhost:8080/ex?label=qwe
     * @param label
     * @return
     */    
    @GetMapping
    public String test(@RequestParam String label) {
        
        return "success";
    }
}
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 400异常处理
     * @param request
     * @param e
     * @return
     */
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class, TypeMismatchException.class, MissingServletRequestParameterException.class})
    public RestResult<String> requestNotReadable(HttpServletRequest request, HttpMessageNotReadableException e) {
        
        log.info("requestNotReadable: "+e.getMessage());  
        return RestResultGenerator.failure(e.getMessage());
    }

修改代码GlobalExceptionHandler.requestNotReadble方法如下

//因为这个方法会对多个异常进行处理,参数2异常类 换成更大的异常类Exception 
public RestResult<String> requestNotReadable(HttpServletRequest request, Exception e) {
        
        log.info("requestNotReadable: "+e.getMessage());  
        return RestResultGenerator.failure(e.getMessage());
    }

 重启再次请求错误的URL:http:localhost:8080/ex

 返回变成自己封装的结果!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值