Spring Boot:发生错误时如何自定义JSON响应(使用ControllerAdvice)

时间:2019-03-29 15:10:47

标签: json rest spring-boot exception httpresponse

使用Spring Boot Rest API:我有一个用于用户登录的端点。当用户的凭据无效时,会引发UnauthorizedException以及自定义消息。

通过使用自定义Exception和ErrorDetails对象,我已相应地设置了错误消息响应。

但是我一直从Spring Boot那里得到一个包含扩展头的JSON响应。如何自定义标头,使其仅返回我想看到的内容?

这是我作为响应返回的JSON消息。但是,我只希望得到错误:{}部分错误。

{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 401,
  "statusText": "OK",
  "url": "http://localhost:8080/access/login",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://localhost:8080/access/login: 401 OK",
  "error": {
    "message": "Invalid username and/or password.",
    "details": "uri=/access/login",
    "timestamp": "2019-03-29T14:52:28.863+0000"
  }
}

{ "headers": { "normalizedNames": {}, "lazyUpdate": null }, "status": 401, "statusText": "OK", "url": "http://localhost:8080/access/login", "ok": false, "name": "HttpErrorResponse", "message": "Http failure response for http://localhost:8080/access/login: 401 OK", "error": { "message": "Invalid username and/or password.", "details": "uri=/access/login", "timestamp": "2019-03-29T14:52:28.863+0000" } }

这是用于ControllerAdvice,ErrorDetails和UnauthorizedException的代码:

public class ErrorDetails {
    private String message;
    private String details;
    private Date timestamp;

    public ErrorDetails(String message, String details, Date timestamp) {
        super();
        this.message = message;
        this.details = details;
        this.timestamp = timestamp;
    }

    public String getMessage() {
        return message;
    }

    public String getDetails() {
        return details;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<ErrorDetails> unauthorizedException(UnauthorizedException e, WebRequest webRequest) {
        ErrorDetails errorDetails = new ErrorDetails(e.getMessage(), webRequest.getDescription(false),new Date());
        return new ResponseEntity<>(errorDetails, HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> globalExceptionHandler(Exception e, WebRequest webRequest) {
        ErrorDetails errorDetails = new ErrorDetails(e.getMessage(), webRequest.getDescription(false),new Date());
        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}



@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends Exception {

    private static final long serialVersionUID = 1L;

    public UnauthorizedException(String message) {
        super(message);
    }
}

1 个答案:

答案 0 :(得分:0)

这是我正常工作的示例:

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

        @ExceptionHandler(value = IllegalArgumentException.class)
        protected ResponseEntity<Object> handleInvalidBody(IllegalArgumentException ex, WebRequest request) {
            return handleExceptionInternal(ex, "Error message", new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
        }
    }

当您扔出IllegalArgumentException时,它会被处理。