Spring在提供请求体时如何抛出错误

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

How to make Spring throw an error when a body is provided

问题

这个控制器不应该接受任何请求体。然而,当我带有请求体调用这个端点时,请求体会被忽略。我该如何让Spring在向不接受请求体的端点提供请求体时抛出错误?

英文:

I have an application with a controller like this:

@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping
    public String handler() {
        return ...;
    }
}

This controller is not supposed to accept any body. However, when I call the endpoint with a body the body is just ignored. How can I make Spring throw an error when providing a body to an endpoint which accepts none?

答案1

得分: 1

我有两个选项供您选择。第一个选项是接受一个带有 Body 参数,然后由您自己处理:

@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping
    public String handler(@RequestBody(required = false) String requestBody) {
        if (requestBody != null && !requestBody.isEmpty()) {
            throw new YourException("This endpoint does not accept a request body.");
        }
        return ...;
    }
}

第二个选项是消耗 Mediatype。在这个选项中,Spring 将显示 'HttpMediaTypeNotSupportedException'。实际上,您可以添加任何 MediaType:

@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String handler() {
        return ...;
    }
}
英文:

I have 2 options for you. The first one is to take a parameter with Body and then handle it by yourself:

@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping
    public String handler(@RequestBody(required = false) String requestBody) {
        if (requestBody != null && !requestBody.isEmpty()) {
            throw new YourException("This endpoint does not accept a request body.");
        }
        return ...;
    }
}

and the second one is to consume Mediatype. In this option, Spring will show 'HttpMediaTypeNotSupportedException'. Actually, you can add any MediaType:

@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String handler() {
        return ...;
    }
}

huangapple
  • 本文由 发表于 2023年4月20日 05:24:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058915.html
匿名

发表评论

匿名网友

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

确定