如何在Spring Boot 中处理MethodArgumentTypeMismatchException并设置自定义错误消息?

oug3syen  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(163)

我正在做一个REST API,当我故意尝试错误的输入来强制错误时,我在这个API中遇到了麻烦:
第一个月
答复的正文如下:

{
    "timestamp": "2023-12-01T22:43:11.433+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: \"43178asdas\"",
    "path": "/objectName/43178asdas"
}

字符串
我想为这个错误创建一个自定义消息,让它更清楚地表明预期的输入是Long类型,但请求收到的却是String类型,但我无法处理这个异常。
我所尝试的:

public class ThisObjectInvalidaException extends TypeMismatchException {
    public ThisObjectInvalidaException(String msg){
        super(msg);
    }
}


public SaidObject consult(Long param) throws ThisObjectInvalidaException {
        try {
            return this.objRepository.findById(identifier)
                    .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No object found with the following IDENTIFIER: " + identifier + "."));
        } catch (TypeMismatchException e){
            throw new ThisObjectInvalidaException("The IDENTIFIER you entered is invalid, as it should contain only numbers.");
        }
    }


也许我在错误类型中遗漏了一些东西,但不确定。

r9f1avp5

r9f1avp51#

您可以简单地将ExceptionException添加到控制器。
范例:

@RestController
public class YourController {

    // Your endpoint mappings

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
        String error = "The IDENTIFIER you entered is invalid, as it should contain only numbers.";
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
}

字符串
作为替代解决方案,您可以创建自定义异常并抛出它。
例二:

public class IdentifierFormatException extends RuntimeException {

    public IdentifierFormatException(String message) {
        super(message);
    }

}


然后将其添加到异常处理程序:

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
        throw new IdentifierFormatException("The IDENTIFIER you entered is invalid, as it should contain only numbers.");
    }

相关问题