使用 @controlleradvice 配合 @exceptionhandler(numberformatexception.class) 即可捕获全局数字格式异常。在配置类中定义一个方法,参数为 numberformatexception 和 httpservletrequest,返回自定义的 json 响应对象,这样所有未处理的数字转换错误都会统一拦截。

如何区分不同业务场景下的数字校验失败
通过检查异常消息或堆栈信息来区分具体的业务失败原因。虽然 @ExceptionHandler能捕获所有 NumberFormatException,但可以通过判断异常来源(如 Integer.parseInt 还是 BigDecimal)来返回不同的错误码,从而让前端知道是输入为空、格式错误还是超出范围。

package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NumberFormatException.class)
public ResponseEntity<map object>> handleNumberFormatException(
NumberFormatException ex, HttpServletRequest request) {
Map<string object> body = new HashMap();
body.put("error", "INVALID_NUMBER_FORMAT");
body.put("message", "The input is not a valid number: " + ex.getMessage());
body.put("path", request.getRequestURI());
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
}</string></map>
当输入包含空格时如何处理
默认情况下 NumberFormatException 不会自动去除空格,导致 " 123 " 报错。可以在捕获异常后尝试调用 trim() 重新解析,或者在入口处统一清洗数据。如果选择在后端处理,需要在异常处理器中增加逻辑判断,若原始值仅含空白字符则视为空或特定错误。

package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@ControllerAdvice
public class TrimNumberExceptionHandler {
@ExceptionHandler(NumberFormatException.class)
public ResponseEntity<map object>> handleWithTrim(
NumberFormatException ex, HttpServletRequest request) {
String originalMessage = ex.getMessage();
if (originalMessage != null && originalMessage.contains("For input string")) {
String part = originalMessage.split("For input string ")[1].replace("\"", "");
if (part.trim().isEmpty()) {
Map<string object> body = new HashMap();
body.put("error", "EMPTY_INPUT");
body.put("message", "Input was empty or whitespace only.");
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
}
// Fallback to standard handling
Map<string object> body = new HashMap();
body.put("error", "INVALID_NUMBER_FORMAT");
body.put("message", ex.getMessage());
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
}</string></string></map>











