Configure error page for @PathVariable type mismatch

自作多情 提交于 2019-12-08 05:06:25

问题


Suppose I have a controller:

@Controller

public class SomeController {

    @RequestMapping(value = "{id}/object.do")
    public String showObject(@PathVariable("id") Integer id,
                            HttpServletRequest request) {
            //do smth
            return "somePage";
        }
}

When "id" is not a Number, but string like "aaa/object.do" Tomcat show me an error - "The request sent by the client was syntactically incorrect."

Is there a way to configure an error page that will be shown only when "id" path variable has incorrect type?


回答1:


You can handle this with @ExceptionHandler for this particular error (I suspect it is TypeMismatchException)

@ExceptionHandler(TypeMismatchException.class)
public ModelAndView handleTypeMismatchException(TypeMismatchException ex) {
    //TODO log
    // Return something reasonable to the end user.
    ...
}

Please note, that @ExceptionHandler basically has almost the same capabilities, as usual handlers:

Much like standard controller methods annotated with a @RequestMapping annotation, the method arguments and return values of @ExceptionHandler methods are very flexible.



来源:https://stackoverflow.com/questions/15431180/configure-error-page-for-pathvariable-type-mismatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!