如果请求标头验证错误,让Spring响应400(而不是500) [英] Have Spring respond with 400 (instead of 500) in case of a request header validation error

查看:148
本文介绍了如果请求标头验证错误,让Spring响应400(而不是500)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对Spring MVC @RequestMapping方法的参数进行验证时,Spring会根据参数的类型以不同的状态代码进行响应:

When using validation for parameters of a Spring MVC @RequestMapping method, Spring responds with with different status codes depending on the type of the parameter:

  • 对于无效的@RequestBody参数,Spring响应为400
  • 对于无效的@RequestHeader@PathVariable@RequestParam参数,Spring响应为500.
  • For invalid @RequestBody parameters, Spring responds with 400
  • For invalid @RequestHeader, @PathVariable, and @RequestParam parameters, Spring responds with 500.

可以更改此设置,以便在所有情况下Spring都以相同的400响应进行响应吗?

Can this be changed so that Spring responds with the same 400 response in all cases?

这是我的代码:

@Controller
@Validated
public class WebController {

    @RequestMapping(method = RequestMethod.POST, path = "/action")
    public ResponseEntity<String> doAction(
            @RequestHeader("Header-Name") @Valid LatinString headerValue,
            @RequestBody @Valid Struct body) {
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

public class LatinString {

    @Pattern(regexp = "[A-Za-z]*")
    private String value;

    public LatinString(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

public class Struct {

    @Pattern(regexp = "[A-Za-z0-9.-]{1,255}")
    private String domain;

    public String getDomain() {
        return domain;
    }
}

推荐答案

我认为可以通过处理异常类型ConstraintViolationException来获取正确的状态代码(400).为此,需要将以下代码添加到@Controller@ControllerAdvice:

I figured that one can get the right status code (400) by handling the exception type ConstraintViolationException. To do this, one needs to add the following code to the @Controller or a @ControllerAdvice:

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<String> onValidationError(Exception ex) {
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }

不幸的是,它没有像错误的@RequestBody请求那样包含不错的错误消息正文,所以我想知道是否有更好的解决方案.

Unfortunately, this doesn't include the nice error message body like for requests with invalid @RequestBody, so I wonder if there is a better solution.

这篇关于如果请求标头验证错误,让Spring响应400(而不是500)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆