Tôi hiện đang cố gắng sử dụng HandlerExceptionResolver
để xử lý ngoại lệ trong dự án Spring MVC.Xử lý ngoại lệ MVC mùa xuân với HandlerExceptionResolver
Tôi muốn xử lý các ngoại lệ thông thường qua resolveException
cũng như 404 qua handleNoSuchRequestHandlingMethod
.
Tùy thuộc vào loại yêu cầu JSON hoặc văn bản/html, phản hồi ngoại lệ phải được trả về một cách thích hợp.
resolveException
hoạt động ngay bây giờ.
Nhưng handleNoSuchRequestHandlingMethod
đang khiến tôi đau đầu. Nó không bao giờ được gọi!
Theo docu phương pháp này nên được gọi là trên 404 lỗi
Tôi đang làm gì sai ...
Đây là những gì tôi có cho đến nay.
public class JsonExceptionResolver implements HandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView resolveException(HttpServletRequest request,
if (exception instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) exception, request, response, handler);
}
...
}
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpServletRequest request,
HttpServletResponse response,
Object handler){
logger.info("Handle my exception!!!");
ModelAndView mav = new ModelAndView();
boolean isJSON = request.getHeader("Accept").equals("application/json");
if(isJSON){
...
}else{
..
}
return mav;
}
}
EDIT với DefaultHandlerExceptionResolver:
public class MyExceptionResolver extends DefaultHandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(getClass());
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
logger.warn("An Exception has occured in the application", exception);
logger.info("exception thrown " + exception.getMessage());
if (exception instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) exception, request, response, handler);
}
...
return mav;
}
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpServletRequest request,
HttpServletResponse response,
Object handler){
logger.info("Handle my exception!!!");
ModelAndView mav = new ModelAndView();
boolean isJSON = request.getHeader("Accept").equals("application/json");
if(isJSON){
...
}else{
...
}
return mav;
}
}
Đoạn mã trên vẫn không có tác dụng.
Bất kỳ ý tưởng nào khác?
tôi cập nhật mã của tôi. Ý bạn là nó như thế này? –
Tôi cũng đã thử nó với kế thừa từ '' DefaultHandlerExceptionResolver'', nhưng trong trường hợp 404 'doResolveException'' không bao giờ được gọi ... tôi có hiểu nhầm bạn không? –