java—如何在globalexceptionhandler中参数化responseentity类

dwbf0jvd  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(309)

下面的类有一个sonarqube错误,我不知道如何参数化。
我需要什么样的东西排队 return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST); ```
@ControllerAdvice
public class GlobalExceptionHandler {

// handling specific exception
@ExceptionHandler(InvalidFieldException.class)
public ResponseEntity<Exception> resourceNotFoundHandling(InvalidFieldException exception, WebRequest request){
    ErrorDetails errorDetails =
            new ErrorDetails(new Date(), HttpStatus.BAD_REQUEST, "Argument Validation failed", exception.getMessage(), request.getDescription(false));
    return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);
}

// handling global exception
@ExceptionHandler(Exception.class)
public ResponseEntity<Exception> globalExceptionHandling(Exception exception, WebRequest request){
    ErrorDetails errorDetails =
            new ErrorDetails(new Date(), HttpStatus.INTERNAL_SERVER_ERROR, "Global Exception", exception.getMessage(), request.getDescription(false));
    return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}

}

vlf7wbxs

vlf7wbxs1#

参数化类型必须与构造函数中传递的对象相同。你用 ErrorDetails 所以你必须使用它:

@ControllerAdvice
public class GlobalExceptionHandler {

    // handling specific exception
    @ExceptionHandler(InvalidFieldException.class)
    public ResponseEntity<ErrorDetails> resourceNotFoundHandling(InvalidFieldException exception, WebRequest request){
        ErrorDetails errorDetails =
                new ErrorDetails(new Date(), HttpStatus.BAD_REQUEST, "Argument Validation failed", exception.getMessage(), request.getDescription(false));
        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }

    // handling global exception
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorDetails> globalExceptionHandling(Exception exception, WebRequest request){
        ErrorDetails errorDetails =
                new ErrorDetails(new Date(), HttpStatus.INTERNAL_SERVER_ERROR, "Global Exception", exception.getMessage(), request.getDescription(false));
        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

相关问题