我想根据响应对象错误动态返回 HTTPStatus 代码,如 400、400、404 等。我被提到了这个问题 - Programmatically change http response status using spring 3 restful但它没有帮助。
我有这个带有@ExceptionHandler
方法的 Controller 类
@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()));
}
ExceptionUtility
是一个类,我有上面使用的两种方法(getMessage
和getCode
)。
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
}
我不想检查 if 条件并相应地返回响应代码,还有其他更好的方法吗?