gpt4 book ai didi

java - REST 处理错误参数

转载 作者:搜寻专家 更新时间:2023-10-31 20:19:48 25 4
gpt4 key购买 nike

在 RESTful 服务中处理错误参数的正确方法是什么?如果发送了错误的数据类型,我现在有一个端点返回 400。

@ResponseBody
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value="/v1/test")
public MyResponse getSomething(@RequestParam BigDecimal bd) {
MyResponse r = new MyResponse();
r.setBd(bd);
return r;
}

如果最终用户传递一个字符串而不是 BigDecimal,那将非常好,响应将返回一个 json,其中包含响应代码、状态以及我希望它包含的任何其他内容,而不仅仅是 400。有没有办法做到这一点?

更新:我最初的想法是包装每个参数,然后检查它是否是该包装类中的正确类型。这似乎有点傻。难道没有一个我可以添加到类路径中的 validator 来识别这样的东西吗?

另外,有一种方法可以很容易地使用我可以自己创建的 Bean 类型来处理这个问题,但是像 BigDecimal 这样的标准类型呢?

UPDATE-2:此更新解决了使用 @ExceptionHandler 的答案。

TestController.java

import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class TestController {

//this is where correct input from user is passed, no binding errors
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value="/v1/test")
public
@ResponseBody
MyResponse getSomething(@RequestParam BigDecimal bd) {
MyResponse r = new MyResponse();
r.setBd(bd);
return r;
}

//this will handle situation when you except number and user passess string (A123.00 for example)
@ExceptionHandler(ServletRequestBindingException.class)
public @ResponseBody MyErrorResponse handleMyException(Exception exception, HttpServletRequest request) {

MyErrorResponse r = new MyErrorResponse();
r.setEexception(exception);

return r;
}


}

TestUnitTest.java

public class TestUnitTest {

protected MockMvc mockMvc;

@Autowired
protected WebApplicationContext wac;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}


@Test
public void test() throws Exception {
String url = "/v1/test?bd=a123.00";

log.info("Testing Endpoint::: " + url);

MvcResult result = mockMvc.perform(get(url))
.andExpect(status().isOk())
.andReturn();

log.info("RESPONSE::: " + result.getResponse().getContentAsString());
}

}

MyResponse.java

import java.math.BigDecimal;

public class MyResponse {

private BigDecimal bd;

public BigDecimal getBd() {
return bd;
}

public void setBd(BigDecimal bd) {
this.bd = bd;
}

}

MyErrorResponse.java

public class MyErrorResponse {

private Exception exception;

public Exception getException() {
return exception;
}

public void setEexception(Exception e) {
this.exception = e;
}

}

最佳答案

像这样使用 Spring @ExceptionHandler 和标准的 @RequestMapping 注解:

//this is where correct input from user is passed, no binding errors
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value="/v1/test")
public
@ResponseBody
MyResponse getSomething(@RequestParam BigDecimal bd) {
MyResponse r = new MyResponse();
r.setBd(bd);
return r;
}

//this will handle situation when there's exception during binding, for example you except number and user passess string (A123.00 for example)
@ExceptionHandler(TypeMismatchException.class)
public
@ResponseBody
MyErrorResponse handleMyException(Exception exception, HttpServletRequest request) {
//....
}

TypeMismatchException 是在尝试设置 bean 属性时抛出的一般异常。您可以进一步概括代码并使用几种方法捕获每个绑定(bind)异常,例如:

@ExceptionHandler(TypeMismatchException.class)
public
@ResponseBody
String typeMismatchExpcetionHandler(Exception exception, HttpServletRequest request) {
return "type mismatch";
}

@ExceptionHandler(MissingServletRequestParameterException.class)
public
@ResponseBody
String missingParameterExceptionHandler(Exception exception, HttpServletRequest request) {
return "missing param";
}

@ExceptionHandler(Exception.class)
public
@ResponseBody
String generalExceptionHandler(Exception exception, HttpServletRequest request) {
return "general exception";
}

非常灵活,允许在签名和返回对象中使用很多参数Annotation Type ExceptionHandler

使用@ResponseBody,您可以返回任何对象,可以序列化为JSON。它只需要在你的类路径中有 jackson 库,但我假设你已经知道了这一点

关于java - REST 处理错误参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com