SpringBoot请求映射错误捕获

时间:2018-08-28 14:46:23

标签: spring rest http spring-boot exception

我有一个这样的方法映射:

@GetMapping(value = {"/toto_list/{toto_name}/tata_list", "/toto_list/{toto_name}/tata_list/{tata_name}"}, produces = {"application/json", "text/json"})
    public ReturnType myMethod(@PathVariable("toto_name") final String _totoName, @PathVariable(value = "tata_name") Optional<String> _tata_name, final HttpServletRequest _request) throws JAXBException, DatatypeConfigurationException, FrontendException, ServletException { 
...
}

我想捕获一个最终的错误映射,以响应BAD_REQUEST。我该怎么办?

当我使用

请求Spring Boot应用程序时
  

http://[IP]:[PORT]/AppName/toto_list/toto1/tata_listERROR

我遇到了HTTP错误406 NOT_FOUND。

日志应用程序:[WARN] [o.s.web.servlet.PageNotFound]在名称为'dispatcherServlet'的DispatcherServlet中未找到具有URI [/ AppName / toto_list / toto1 / tata_listERROR]的HTTP请求的映射

如何捕获此异常以响应BAD_REQUEST而没有NOT_FOUND?

谢谢

1 个答案:

答案 0 :(得分:0)

只要您的客户端以/ toto_list开头,您就可以编写另一个RequestMapping,例如,抛出404,而该404不会落入控制器中的任何其他映射中

@RequestMapping("/toto_list")
public class MyController() {

/**
    catch every url other than /toto_list/hello and /toto_list/bye and return 404
*/
@RequestMapping(value="**",method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public void didNotMatchAnything(){
  throw new ResourceNotFoundException(); ;
}

@RequestMapping(value="/hello",method = RequestMethod.GET)
public void hello(){
  //do something
}

@RequestMapping(value="/bye",method = RequestMethod.GET)
public void bye(){
  //do something
}

}