Spring ExceptionHandler和Rest响应的异常

时间:2015-09-21 07:20:26

标签: java spring rest exception exception-handling

我使用@ExceptionHandler来管理我的所有异常,并为任何抛出异常的REST API返回JSON响应。 目前我管理两个异常,第一个是ResourceNotFoundException,它可以工作,但第二个,FileExtensionException,它不起作用。 它在eclipse控制台中抛出此异常,而没有任何其他响应。

  

2015-09-21 09:09:05.197 ERROR 7500 --- [nio-8080-exec-2]   .m.m.a.ExceptionHandlerExceptionResolver:无法调用   @ExceptionHandler方法:public matlab.ErrorResponse   matlab.ErrorController.errorHandler(java.lang.Exception的)

     

org.springframework.web.HttpMediaTypeNotAcceptableException:无法   找到可接受的代表   org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:173)     在   org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)     在   org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:185)     在   org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)     在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)     在   org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:362)     在   org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)     在   org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:138)     在   org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)     在   org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1183)     在   org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1020)     在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)     在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)     在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)     在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:622)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:116)     在   org.springframework.boot.context.web.ErrorPageFilter.access $ 000(ErrorPageFilter.java:60)     在   org.springframework.boot.context.web.ErrorPageFilter $ 1.doFilterInternal(ErrorPageFilter.java:91)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)     在   org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)     在   org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:673)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1526)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1482)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:745)

     

2015-09-21 09:09:05.201 ERROR 7500 --- [nio-8080-exec-2]   o.s.boot.context.web.ErrorPageFilter:转发到错误页面   来自请求[/ ManagmentFile / zipDownload]由于异常[The   所选文件具有不同的扩展名:xlsx而不是zip]

     

matlab.FileExtensionException:所选文件有不同   扩展名:xlsx而不是拉链   matlab.FileServices.getZipFile(FileServices.java:46)at   matlab.ws.FileManagerImpl.getZip(FileManagerImpl.java:38)at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:497)at   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)     在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)     在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)     在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)     在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)     在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)     在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)     在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)     在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:622)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:116)     在   org.springframework.boot.context.web.ErrorPageFilter.access $ 000(ErrorPageFilter.java:60)     在   org.springframework.boot.context.web.ErrorPageFilter $ 1.doFilterInternal(ErrorPageFilter.java:91)     在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)     在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:109)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)     在   org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)     在   org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:673)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1526)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1482)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:745)

这些是webservices调用的代码:

public FileSystemResource getZipFile(String fileName) throws FileExtensionException {
    String ext=FilenameUtils.getExtension(fileName);
    if (ext!= "zip")
        throw new FileExtensionException(ext + " and not zip");
    return new FileSystemResource(new File(fileName));
}

例外:

package matlab;

public class FileExtensionException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public FileExtensionException(String message){
        super("The selected file has a different extension:" + message);
    }
}

RestController:

@RequestMapping(value = "/files", method = RequestMethod.GET)
public Response<Collection<FileModel>> getAllFiles(@RequestParam(value="path", defaultValue="/home") String path) throws ResourceNotFoundException {
    Collection<FileModel> result;
    result = file.getAllFiles(path);
    return new Response<Collection<FileModel>>(HttpStatus.OK.value(),result);
}

@RequestMapping(value = "/zipDownload", produces="application/zip", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getZip(@RequestParam(value="filePath", required=true) String filePath ) throws FileExtensionException{
    return file.getZipFile(filePath);
}

ResourceNotFoundException

public class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(String path){
        super("The specified path: "+ path +"  doesn't exist");
    }
}

ErrorControl

@ControllerAdvice 
public class ErrorController {

    /**
     * 
     * @param e: exception thrown
     * @return ErroreResponse
     */
    @ExceptionHandler(Exception.class)
    public @ResponseBody ErrorResponse errorHandler(Exception e){   
        //Make the exception by buildErrorResponse
        return ErrorResponseBuilder.buildErrorResponse(e);
    }

}

错误构建:

public class ErrorResponseBuilder {

    public ErrorResponseBuilder() { 
    }

    /**
     * Build exception response beginning from exception
     * @param e exception thrown
     * @return ErrorResponse: response of an exception
     */
    public static ErrorResponse buildErrorResponse(Exception e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        return new ErrorResponse(HttpStatusManager.getHttpCode(e),e.getClass().getName(),e.getMessage(),errors.toString());
    }

}

问题出在哪里? 感谢

1 个答案:

答案 0 :(得分:1)

尝试使用以下命令更新弹簧配置:

<bean id="methodHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter"/>
                <ref bean="jsonHttpMessageConverter"/>
                <ref bean="marshallingHttpMessageConverter"/>
            </list>
        </property>
    </bean>