错误请求导致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
返回变成自己封装的结果!