Java – exceptionhandler in spring

import org.springframework.beans.TypeMismatchException;
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 Execute the function handlemyexception. As expected

But if I call http://example.com/aa/bb/QQQ I want to call the function handletypemismatch exception, but I call handleexception of type typemismatch exception

An annoying solution is to test the type of exception in handleexception (). If the exception type is typemismatch exception, call handletypemismatch exception

But why does it work now? Select exception handler at runtime according to the type of exception? Or at compile time?

Solution

From official spring documentation:

Before actually executing the method, the exception you try to catch is generated by spring itself (string to double conversion) Catch it does not conform to the specification of @ exceptionhandler This really makes sense - usually you don't want to catch exceptions generated by the framework itself

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>