我有简单的 Spring Controller 。
@GetMapping("/test")
@ResponseBody
public String doSomething(@RequestParam int a) {
return String.valueOf(a);
}
当我在查询字符串中传递 a=1 时,它工作正常。
但是当我通过 a=abc 时,它给了我这个。
> Failed to convert value of type 'java.lang.String' to required type
> 'int'; nested exception is java.lang.NumberFormatException: For input
> string: "abc".
有没有办法让我可以处理这个错误并向用户响应,就像必须是数字一样。
提前致谢。
最佳答案
您可以使用@ControllerAdive
来处理此类异常。
@ControllerAdvice
public class RestControllerAdive extends ResponseEntityExceptionHandler
{
@ExceptionHandler(value=NumberFormatException.class)
public ResponseEntity<Object> handleNumberFormatException(NumberFormatException ex)
{
return new ResponseEntity({your-error-message}, HttpStatus);
}
}
关于java - 如何处理spring Controller 参数类型异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45441263/