3

通常のリクエストと残り/ajaxリクエストの両方で例外を処理したい。ここに私のコードがあります、

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleCustomException(Exception ex) {

        ModelAndView model = new ModelAndView("error");
        model.addObject("errMsg", ex.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        sw.toString();
        model.addObject("errTrace", sw);
        return model;

    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAjaxException(Exception ex) {
        JSONObject model = new JSONObject();
        model.put("status", "error");
        model.put("errMsg", ex.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        sw.toString();
        model.put("errTrace", sw);

        return model.toString();
    }
}

@ExceptionHandler(Exception.class) を2回使用できないため、これによりエラーが発生します。では、解決策は何でしょうか?

4

4 に答える 4

2

これは、Spring mvc のグローバルな例外ハンドラです。これは、アプリケーションで例外が検出されるたびに呼び出されます。web.xml の助けを借りて、404 例外のみを制御すると思います。

@ControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ModelAndView handleAllException(Throwable ex,
            HttpServletResponse response) {

        ex.printStackTrace();
        // Set Status
        response.setStatus(500);
        // Set View
        ModelAndView model = new ModelAndView("500");
        model.addObject("navlabel", "");
        model.addObject("userActivity", new ArrayList<String>());
        // Set exception Message
        model.addObject("errMsg", ex.getMessage());
        return model;
    }
}
于 2015-08-18T11:33:08.713 に答える