2016-09-20 116 views
0

我希望根据响应对象r错误,像400,400,404等动态返回HTTPStatus代码。 Ive提到这个问题 - Programmatically change http response status using spring 3 restful但它没有帮助。根据请求使用@ExceptionHandler动态返回HTTP状态代码

伊夫这个控制器类@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())); 
    } 

ExceptionUtility就是我上面使用的两种方法=的getMessage和引用代码

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 ? 
    } 

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

回答

0

您需要定义不同的异常处理程序不同的异常,然后下面用@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; 
    } 
+0

是不是有更好的办法比这个? – user2340345

+0

这是Spring Exception Handler的工作原理。如果你使用春天,你可以用这个。 – Suraj