Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC ExceptionHandler for restful and normal

I want to handle exception for both normal and rest/ajax requests. Here is my code,

@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();
    }
}

This will give me an error as I cant have @ExceptionHandler(Exception.class) twice. So what could be the solution?

like image 828
odedravijay Avatar asked Nov 20 '25 14:11

odedravijay


1 Answers

see the configuration of @ControllerAdvice: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

So you can create two classes(error handlers) and specify annotations/basePackages/assignibaleTypes

For example for REST(ajax) use @RestController annotation for your controllers and you can handle errors like this:

@ControllerAdvice(annotations = RestController.class)
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAjaxException(Exception ex) {
        ...
    }
}

for other cases it can be error handler with annotation

@ControllerAdvice(annotations = Controller.class)
like image 130
Anatoly Deyneka Avatar answered Nov 22 '25 04:11

Anatoly Deyneka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!