2014-04-07 79 views
1

我有這個REST控制器也應該處理異常。Spring REST多部分錯誤處理

@ExceptionHandler(MultipartException.class)註釋不起作用explained

因此,我正在實施HandlerExceptionResolver,它基本上正在工作,但對於@ExceptionHandler而言,不如REST和JSON響應便利。

我想返回我的自定義類ValidationReportresolveException類似於@ExceptionHandler handleBadRequest。我無法創建一個ModelAndView,其中包含一個ValidationReport json響應。任何想法如何結合這兩種風格?

@RestController 
class ValidationController implements HandlerExceptionResolver{ 
    static Logger LOG = LoggerFactory.getLogger(ValidationController.class); 


@RequestMapping(value="/validate", method=[POST]) 
public ValidationReport validate(MultipartFile file) { 
    LOG.info("received file ${file?.name}") 
    ValidationReport report = new ValidationReport(); 
    return report 
} 


@ResponseStatus(BAD_REQUEST) 
@ExceptionHandler(MultipartException.class) 
@ResponseBody ValidationReport handleBadRequest(HttpServletRequest req, Exception ex) { 
    return new ValidationReport(USER_ERROR, "you should not upload files bigger then xx MB") 
} 

@Override 
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 
    if (ex instanceof MultipartException){ 
     response.sendError(BAD_REQUEST.value(),ex.message) 
    } 
    return null 
} 
} 

回答

0

這不是一個解決方案,我不快樂的事情,但一個工程。我實現了HandlerExceptionResolver接口來捕獲所有異常。

在實現的方法中,我只處理我感興趣的異常。然後我向調用者發送錯誤代碼並告訴他他做了什麼錯誤。

@Override 
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 

    if (ex instanceof MultipartException){ 
     response.sendError(413,"Content is to big. Maximal allowed request size is: ${Application.MAX_REQUEST_SIZE}") 
    } 
}