Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - Spring boot @ExceptionHandler not responding with custom response

I have a global exception handler with @RestControllerAdvice and @ExceptionHandler(APIException.class) methods. I have designed my own response class ValidationResponse.class which I am adding to Response entity class. I want to respond with ValidationResponse but getting some generic response instead.

Global Exception Handler

@RestControllerAdvice
public class RestResponseExceptionHandler {

    @ExceptionHandler(APIException.class)
    public ResponseEntity<ValidationResponse> handleException(APIException ex) {
        ValidationResponse validationResponse = new ValidationResponse(ex.getErrorCode(), ex.getErrorMessage());
        return new ResponseEntity<>(validationResponse, ex.getHttpStatus());
    }
}

Custom exception class

@Getter
@Setter
public class APIException extends RuntimeException {

    private int errorCode;

    private String errorMessage;

    private HttpStatus httpStatus;

    public APIException(int errorCode, String errorMessage, HttpStatus httpStatus) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.httpStatus = httpStatus;
    }

    public APIException(int errorCode, String errorMessage, HttpStatus httpStatus, Exception e) {
        super(e);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.httpStatus = httpStatus;
    }

}

Custom response design

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(Include.NON_NULL)
public class ValidationResponse {

    public int errorCode;

    public String errorMessage;
}

Expected response

{
    "errorCode": 1010,
    "errorMessage": "some custome validation message"
}

Current Response

{
  "error-message" : "Request processing failed; nested exception is com.package.exception.APIException",
  "error-code" : "GENERAL_ERROR",
  "trace-id" : null,
  "span-id" : null
}
question from:https://stackoverflow.com/questions/65932575/spring-boot-exceptionhandler-not-responding-with-custom-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(APIException.class)
    public ResponseEntity<ValidationResponse> handleException(APIException ex, WebRequest webRequest) {

    }
}

Try this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...