我是春天新手。我正在使用spring webmvc开发REST api。对于错误处理,我得到了这个链接http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-rest-spring-mvc-exceptions
我试图在我的项目中使用ResponseEntityExceptionHandler。但是每当我的控制器抛出异常时,它就永远不会到达这个ResponseEntityExceptionHandler。
以下是我的代码段
控制器
@Controller
@RequestMapping("/hello")
public class HelloController {
private static final Logger logger = Logger.getLogger(HelloController.class);
@RequestMapping(value="/{name}", method=RequestMethod.GET)
public @ResponseBody String greet(@PathVariable(value = "name")String name ) throws InvalidInputException, ResourceNotFoundException{
logger.info("start greet() "+name );
System.out.println("start greet() "+name);
String message = null;
if("".equalsIgnoreCase(name))
{
throw new InvalidInputException("Invalid Input");
}
List<String> names = new ArrayList<String>();
names.add("Harshal");
names.add("Smitesh");
if(names.contains(name)){
message = "Hello "+ name;
}else{
throw new ResourceNotFoundException("Requested Resource not found");
}
System.out.println("end greet");
logger.info("end greet()");
return message;
}
}
例外
package com.practice.errorhandlerdemo.exception;
public class InvalidInputException extends RuntimeException{
private static final long serialVersionUID = 5489516240608806490L;
public InvalidInputException() {
super("Invalid Input");
}
public InvalidInputException(String message) {
super(message);
}
}
package com.practice.errorhandlerdemo.exception;
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = -4041009155673754859L;
public ResourceNotFoundException() {
super("requested resource not found");
}
public ResourceNotFoundException(String message) {
super(message);
}
}
的ExceptionHandler
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger logger = Logger.getLogger(RestResponseEntityExceptionHandler.class);
@ExceptionHandler(value={ResourceNotFoundException.class})
@ResponseStatus(value=HttpStatus.NOT_FOUND)
protected ResponseEntity<Object> handleResourceNotFound(RuntimeException ex, WebRequest request){
logger.info("start handleResourceNotFound()");
String bodyOfResponse = "Requested resource does not found";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return handleExceptionInternal(ex, bodyOfResponse, httpHeaders, HttpStatus.NOT_FOUND, request);
}
@ExceptionHandler(value={InvalidInputException.class})
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleInvalidInput(RuntimeException ex, WebRequest request){
logger.info("start handleInvalidInput()");
String bodyOfResponse = "Invalid Input";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
return handleExceptionInternal(ex, bodyOfResponse, httpHeaders, HttpStatus.BAD_REQUEST, request);
}
}
调度程序servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.practice.errorhandlerdemo.controller"/>
<context:annotation-config/>
</beans>
的web.xml
<web-app>
<display-name>ErrorHandlerDemo</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/my-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:6)
首先,检查您的@ControllerAdvice
带注释的类是否被您的配置考虑在内:它是否位于Spring扫描的软件包中?你是否以任何其他方式将其声明为bean?
此外,如果您不需要提供所有异常映射,则无需延长ResponseEntityExceptionHandler
。
编写异常处理的简单方法:
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
protected ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex){
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("Requested resource does not found");
}
@ExceptionHandler(InvalidInputException.class)
protected ResponseEntity<String> handleInvalidInput(InvalidInputException ex){
return ResponseEntity
.badRequest()
.body("Invalid Input");
}
}
请注意,{4.1}引入了ResponseEntity
构建器API,但您可以在4.0.x上使用常规构造函数。
答案 1 :(得分:1)
我在Spring WebMVC 4.2.5中遇到了同样的问题。原因是throwExceptionIfNoHandlerFound
的{{1}}参数。默认情况下,它的值为DispatcherServlet
,因此所有错误都会生成false
servlet响应,并且没有异常抛出。
我将其设置为true后,我的HttpServletResponse.SC_NOT_FOUND
开始工作
答案 2 :(得分:1)
问题在于您的@ExceptionHandler声明ResourceNotFoundException,而作为handleResourceNotFound的参数,您期望RuntimeException。参数exception和ExceptionHandler的值应该匹配。
所以应该是:
@ExceptionHandler(value={ResourceNotFoundException.class})
protected ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request){
}
答案 3 :(得分:0)
在某些情况下,ResponseEntityExceptionHandler
和@ControllerAdvice
都无效。
他们都应该将在类下用@ExceptionHandler
注释的方法编译成一个所有控制器都可以引用的公共位置。
如果它不适合你。您可以将@ExceptionHandler
方法添加到由所有其他控制器扩展的公共AbstractController
类中。
答案 4 :(得分:0)
您只需要一些配置
在application.properties或application.yml中:
List<String>
在springboot上加载您的配置文件:
public static String[] listarArchivos() throws IOException {
List<String> al = new ArrayList<>();
if (documento.exists()) {
File[] listadoDeFiles = documento.listFiles();
for (File ficheroRuta : listadoDeFiles) {
File fichero = new File(documento.getPath()
+ sep + ficheroRuta.getName());
if (fichero.isFile()) {
al.add(fichero.getPath());
}
}
}
return al.toArray(new String[0]);
}
答案 5 :(得分:0)
一些解决方法,
ResponseEntityExceptionHandler
。ResponseEntityExceptionHandler::handleException
方法设置断点。NoHandlerFoundException
,您应该将 DispatcherServlet 配置为在找不到任何处理程序时抛出异常,link here。