如何在 REST 中显示自定义错误响应 API

How to display customized error response in REST API

我的url是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"
        }
    ]
}

以下示例代码演示了如何为异常处理自定义错误消息。

  • 为您的自定义响应创建 2 个 POJO body。
  • 实施 1 种方法以捕获 MissingServletRequestParameterException 异常,并为缺少的参数添加 @ExceptionHandler 注释。
  • 按预期生成响应。

Class: ResponseProperty.java

public class ResponseProperty {
    private int id;

    private String detail;

    private int status;

    //getters and setters produced by IDE
}

Class: 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
        }
    ]
}

希望对您有所帮助! :)

更新
如果要从header获取名为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")));
    ...
}