ExceptionHandler in Spring

import org.springframework.beans.TypeMismatchException;
import javax.annotation.*;
import javax.servlet.http.*;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/aa")
public class BaseController {

    @RequestMapping(value = "/bb/{number}", method = RequestMethod.GET, produces = "plain/text")
    public void test(@PathVariable final double number, final HttpServletResponse response) throws IOException {
        throw new MyException("whatever");
    }

    @ResponseBody
    @ExceptionHandler(MyException.class)
    public MyError handleMyException(final MyException exception, final HttpServletResponse response) throws IOException {
        ...
    }

    @ResponseBody
    @ExceptionHandler(TypeMismatchException.class)
    public MyError handleTypeMismatchException(final TypeMismatchException exception, final HttpServletResponse response) throws IOException {
        ...
    }

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    @ExceptionHandler
    public MyError handleException(final Exception exception) throws IOException {
        ...
    }
}

If I call http://example.com/aa/bb/20 , the handleMyException function executes as expected.

However, if I call http://example.com/aa/bb/QQQ I would expect the function to be handleTypeMismatchExceptioncalled, but handleException is thrown instead, except for the type TypeMismatchException.

An unpleasant workaround to do this would be to check the type of exception inside handleException(), and call handleTypeMismatchExceptionif the exception is of type TypeMismatchException.

but why does it work now? is the exception device selected at runtime according to the type of exception? or is it selected at compile time?

+5
source share
1 answer

spring:

@ExceptionHandler ,

, , spring ( ) . @ExceptionHandler. - , , .

+3

All Articles