我的网址是http://localhost:8090/employee/?emp_id=1551&name=
我使用Spring启动来设计REST应用程序。我已经使用@RequestMapping和@RequestParam注释来获取资源。当我将空值传递给请求参数(例如,name =)时,我得到以下验证响应(下面的实际输出部分)。
但是我想覆盖此输出以显示自定义错误响应,如下所示(预期部分如下) 我怎样才能做到这一点?如何避免Spring在Get请求中对输入参数进行自动验证?
Output
======
{
"timestamp": 1511144660708,
"status": 400,
"error": "Bad Request",
"message": "Required String parameter 'name' is not present",
"path": "/employee"
}
Expected
========
{
"errors":[
{
"id":"123144",
"detail": "invalid user input"
"status": "400"
}
]
}
答案 0 :(得分:0)
以下示例代码演示了如何自定义异常处理的错误消息。
MissingServletRequestParameterException
注释实现1方法以捕获缺少参数的@ExceptionHandler
注释。类:ResponseProperty.java
public class ResponseProperty {
private int id;
private String detail;
private int status;
//getters and setters produced by IDE
}
类:ResponsePOJO.java
public class ResponsePOJO {
List<ResponseProperty> errors;
public List<ResponseProperty> getErrors() {
return errors;
}
public void setErrors(List<ResponseProperty> errors) {
this.errors = errors;
}
}
方法:handleMethodArgumentTypeMismatch
@ExceptionHandler({ MissingServletRequestParameterException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(MissingServletRequestParameterException ex) {
ResponseProperty property = new ResponseProperty();
property.setId(123144);
property.setDetail("invalid user input");
property.setStatus(400);
ResponsePOJO responsePOJO = new ResponsePOJO();
List<ResponseProperty> propertyList = new ArrayList<ResponseProperty>();
propertyList.add(property);
responsePOJO.setErrors(propertyList);
return new ResponseEntity<Object>(responsePOJO, HttpStatus.BAD_REQUEST);
}
如果您访问没有必需参数的端点/employee
,那么您将看到如下响应:
Http响应
{
"errors": [
{
"id": 123144,
"detail": "invalid user input",
"status": 400
}
]
}
希望这对你有所帮助! :)
<强>更新强>
如果您想从名为 requestId 的标题中获取请求ID以获取响应,则可以使用WebRequest
获取此信息,如下所示:
@ExceptionHandler({ MissingServletRequestParameterException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(MissingServletRequestParameterException ex,
WebRequest request) {
ResponseProperty property = new ResponseProperty();
property.setId(Integer.valueOf(request.getHeader("requestId")));
...
}