如何在Spring Boot中捕获Bad Request

huangapple go评论68阅读模式
英文:

How to catch Bad Request in Spring Boot

问题

以下是您提供的内容的中文翻译:

我正在创建一个简单的REST服务,可以在用户上执行CRUD操作。

要创建用户,我编写了以下函数:

@PostMapping(path = "/new")
public @ResponseBody ResponseEntity<User> createUser(@RequestParam String name, @RequestParam String email, @RequestParam String password, @RequestParam String platform, @RequestParam String platformID, @RequestParam String wishlist) {
    if(name != "" && email != "" && password != "" && platform != "" && platformID != "" && wishlist != "") {
        User user = new User(name, email, password, platform, platformID, wishlist);
        User result = userRepository.save(user);
        return new ResponseEntity<User>(result, HttpStatus.CREATED);
    }
    return new ResponseEntity("无法添加用户,因为信息不完整", HttpStatus.CONFLICT);
}

如您所见,我在请求参数中提供了用户信息。我希望在请求的URL中有参数缺失时执行函数的底部代码。然而,当参数缺失时,我会自动收到“Bad Request”HTTP错误。是否有人知道如何捕获这样的错误或更改其中的文本?

英文:

I'm creating a simple REST Service where I can do crud operations over users.

For creating users, I wrote the following function:

    public @ResponseBody ResponseEntity&lt;User&gt; createUser(@RequestParam String name, @RequestParam String email, @RequestParam String password, @RequestParam String platform, @RequestParam String platformID, @RequestParam String wishlist) {
        if(name != &quot;&quot; &amp;&amp; email != &quot;&quot; &amp;&amp; password != &quot;&quot; &amp;&amp; platform != &quot;&quot; &amp;&amp; platformID != &quot;&quot; &amp;&amp; wishlist != &quot;&quot;) {
            User user = new User(name, email, password, platform, platformID, wishlist);
            User result = userRepository.save(user);
            return new ResponseEntity&lt;User&gt;(result, HttpStatus.CREATED);
        }
        return new ResponseEntity(&quot;The user can not be added because it is not complete&quot;, HttpStatus.CONFLICT);
    }

As you see, I provide the user info in the request parameters. I want to have it so that if there is a parameter missing in the requested URL, the bottom line of the function is executed. However, when parameters are missing I automatically get back a Bad Request http error. Does anybody know how to catch such an error or change the text in it?

答案1

得分: 0

默认情况下,@RequestParam 是必需的(属性 required = true)。您可以这样做:@RequestParam(required = false)

更新1:我还注意到您在使用 != 来比较字符串。您应该使用类似这样的方式:user != null && !user.equals("")

英文:

by default @RequestParam is required (property required = true). You can do something like this @RequestParam(required = false)

UPDATE 1: I also notice that you use != to compare string. you have to use something like user != null &amp;&amp; !user.eqauls(&quot;&quot;)

答案2

得分: 0

我更喜欢使用 @ControllerAdvice/@RestControllerAdvice

它允许您在整个应用程序范围内处理异常,并且您可以从此处理程序自定义向客户端发送的响应。将其视为一种拦截器。

请检查以下代码示例

@RestControllerAdvice
public class ErrorHandler {

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity<ErrorResponse> illegalArgumentExceptionHandler(IllegalArgumentException e) {
        // ErrorResponse是自定义响应模型
        return new ResponseEntity<>(new ErrorResponse(ErrorCode.NOT_FOUND, e.getMessage()), HttpStatus.NOT_ACCEPTABLE);
    }

}
英文:

I prefer use @ControllerAdvice/@RestControllerAdvice

It allows you to handle exceptions across the whole application and you can customize the response to your client from this handler. Think this as a kind of interceptor.

Please check the following sample code snippet

@RestControllerAdvice
public class ErrorHandler {

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity&lt;ErrorResponse&gt; illegalArgumentExceptionHandler(IllegalArgumentException e) {
           //ErrorResponse is the custom response model
            return new ResponseEntity&lt;&gt;(new ErrorResponse(ErrorCode.NOT_FOUND, e.getMessage()), HttpStatus.NOT_ACCEPTABLE);
     }
    
}

huangapple
  • 本文由 发表于 2020年9月25日 17:28:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64061461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定