Java 使用@ExceptionHandler根据请求动态返回HTTP状态代码

Java 使用@ExceptionHandler根据请求动态返回HTTP状态代码,java,spring,http-status-codes,exceptionhandler,Java,Spring,Http Status Codes,Exceptionhandler,我想根据响应对象错误动态返回HTTPStatus代码,如400、400、404等。 有人向我提出了这个问题,但没有帮助 我有一个带有@ExceptionHandler方法的控制器类 @ExceptionHandler(CustomException.class) @ResponseBody public ResponseEntity<?> handleException(CustomException e) { return new ResponseE

我想根据响应对象错误动态返回HTTPStatus代码,如400、400、404等。 有人向我提出了这个问题,但没有帮助

我有一个带有
@ExceptionHandler
方法的控制器类

@ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<?> handleException(CustomException e) {
        return new ResponseEntity<MyErrorResponse>(
                new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
                ExceptionUtility.getHttpCode(e.getCode()));
    }

我不想签入if条件并相应地返回响应代码,是否有其他更好的方法来执行此操作?

您需要为不同的异常定义不同的异常处理程序,然后使用
@ResponseStatus
,如下所示:

@ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler({ UnAuthorizedException.class })
    public @ResponseBody ExceptionResponse unAuthorizedRequestException(final Exception exception) {

        return response;
    }

@ResponseStatus(HttpStatus.CONFLICT)
    @ExceptionHandler({ DuplicateDataException.class })
    public @ResponseBody ExceptionResponse DuplicateDataRequestException(final Exception exception) {

        return response;
    }

@ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({ InvalidException.class })
    public @ResponseBody ExceptionResponse handleInvalidException(final Exception exception) {

        return response;
    }

这里的
invalideException.class
DuplicateDataException.class
等就是例子。您可以定义自定义异常并从控制器层抛出它们。例如,您可以定义一个
UserAlreadyExistsException
并从异常处理程序返回
HttpStatus.CONFLICT
错误代码。

您的
@ExceptionHandler
方法需要两件事: (i) 具有一个
HttpServletResponse
参数,以便您可以设置响应状态代码;和(ii)没有
@ResponseStatus
注释

@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(HttpServletResponse resp, CustomException e) {
    resp.setStatus(ExceptionUtility.getHttpCode(e.getCode()).value());
    return new ResponseEntity<MyErrorResponse>(
            new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
            ExceptionUtility.getHttpCode(e.getCode()));
}

第一种方法:

您可以在customException类中获取HTTPStatus字段。例如

    class CustomException {
         HttpStatus httpStatus;
         ....other fields
    }
您可以抛出如下错误:

throw new CustomException(otherField , HttpStatus.CREATED);
在异常处理程序中,您可以执行以下操作:

@ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<?> handleException(CustomException e) {
        return new ResponseEntity<MyErrorResponse>(
                new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
                e.getHttpStatus());
    }
HttpStatus getHttpStatus(String code) {
   return ErrorCode.valueOf(code.toUpperCase()).getHttpStatus();
}
然后您可以将异常处理程序修改为

@ExceptionHandler(CustomException.class)
        @ResponseBody
        public ResponseEntity<?> handleException(CustomException e) {
            return new ResponseEntity<MyErrorResponse>(
                    new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
                    e.getHttpStatus());
        }

很抱歉,我错过了上述方法中的空指针异常,但您可以根据需要修改它,只是给出一个想法而已。:)

难道没有比这更好的方法吗?这就是Spring异常处理程序的工作方式。如果您使用的是spring,您可以这样做。当您否决某个答案时,请说明原因。@Suraj这是处理异常的常规方法。在这种情况下,基于exception类中的信息,将状态代码设置为“静态”而不是“动态”。
public enum ErrorCode {


    MyErrorCode(HttpStatus.OK);

    HttpStatus status;

//getter for httpstatus
}
@ExceptionHandler(CustomException.class)
        @ResponseBody
        public ResponseEntity<?> handleException(CustomException e) {
            return new ResponseEntity<MyErrorResponse>(
                    new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
                    e.getHttpStatus());
        }
HttpStatus getHttpStatus(String code) {
   return ErrorCode.valueOf(code.toUpperCase()).getHttpStatus();
}