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

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

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

  1. // handling specific exception
  2. @ExceptionHandler(InvalidFieldException.class)
  3. public ResponseEntity<Exception> resourceNotFoundHandling(InvalidFieldException exception, WebRequest request){
  4. ErrorDetails errorDetails =
  5. new ErrorDetails(new Date(), HttpStatus.BAD_REQUEST, "Argument Validation failed", exception.getMessage(), request.getDescription(false));
  6. return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);
  7. }
  8. // handling global exception
  9. @ExceptionHandler(Exception.class)
  10. public ResponseEntity<Exception> globalExceptionHandling(Exception exception, WebRequest request){
  11. ErrorDetails errorDetails =
  12. new ErrorDetails(new Date(), HttpStatus.INTERNAL_SERVER_ERROR, "Global Exception", exception.getMessage(), request.getDescription(false));
  13. return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
  14. }

}

vlf7wbxs

vlf7wbxs1#

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

  1. @ControllerAdvice
  2. public class GlobalExceptionHandler {
  3. // handling specific exception
  4. @ExceptionHandler(InvalidFieldException.class)
  5. public ResponseEntity<ErrorDetails> resourceNotFoundHandling(InvalidFieldException exception, WebRequest request){
  6. ErrorDetails errorDetails =
  7. new ErrorDetails(new Date(), HttpStatus.BAD_REQUEST, "Argument Validation failed", exception.getMessage(), request.getDescription(false));
  8. return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
  9. }
  10. // handling global exception
  11. @ExceptionHandler(Exception.class)
  12. public ResponseEntity<ErrorDetails> globalExceptionHandling(Exception exception, WebRequest request){
  13. ErrorDetails errorDetails =
  14. new ErrorDetails(new Date(), HttpStatus.INTERNAL_SERVER_ERROR, "Global Exception", exception.getMessage(), request.getDescription(false));
  15. return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
  16. }
  17. }
展开查看全部

相关问题