2016-11-15 71 views
1

后,我写了下面的类:春天开机默认的异常处理

@ControllerAdvice 
public class RestExceptionHandler extends ResponseEntityExceptionHandler { 
    @ExceptionHandler(value = Exception.class) 
    @ResponseBody 
    public ResponseEntity<Object> exceptionHandler(Exception e) { 
     HashMap<String, Object> msg = new HashMap<>(2); 
     msg.put("error", HttpStatus.PRECONDITION_FAILED.value()); 
     msg.put("message", "Something went wrong"); 
     return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST); 
    } 
} 

的意图是在JSON响应发送msg,而不是放弃Spring异常是什么原因引发的。

但是,这门课并不适用。

当我打,说,和无效的端点我的服务器API,我得到默认响应有效载荷:

{ 
    "timestamp": 1449238700342, 
    "status": 405, 
    "error": "Method Not Allowed", 
    "exception": "org.springframework.web.HttpRequestMethodNotSupportedException", 
    "message": "Request method 'POST' not supported", 
    "path": "/bad_enpoint" 
} 

我缺少什么?

谢谢。

+0

你能详细说明“没有工作”吗?它不会被叫?它确实,但失败了? –

+0

我用更多的信息更新了这个问题。它不会被调用,我仍然是Spring默认的JSON,并且Spring的Expect被“暴露” – sargas

回答

1

,因为要映射Exception到您的自定义错误响应您的处理程序不会被调用,但Spring MVC很可能已经有一个注册为Exception类的异常处理程序。它也有一个处理HttpRequestMethodNotSupportedException肯定。

但是,不管怎样,重写整个Spring MVC异常处理/映射并不是一个好主意。您应该只关心特定的例外 - 您定义的例外。

请阅读this article了解Spring MVC异常处理。

+1

感谢您的文章,我很喜欢Spring有自己的处理程序。然而,我不喜欢这样一个事实,即Spring通过发送类似于“exception”的响应来释放应用程序的内部:“org.springframework.web.HttpRequestMethodNotSupportedException”,' – sargas

+0

好吧,它是一个有效点。尝试使用HIGHEST PRECEDENCE集添加@Order注释。看到这个答案:http://stackoverflow.com/questions/19498378/setting-precedence-of-multiple-controlleradvice-exceptionhandlers –

+0

这个链接使用'@ Order'正是我需要的。 – sargas

1
  1. 您不需要扩展ResponseEntityExceptionHandler以使其工作。
  2. 设置两个HttpStatuses是一个坏主意。

@ControllerAdvice(我不知道为什么我必须把它separetly有正确的格式)

public class RestExceptionHandler { 
    @ExceptionHandler(value = Exception.class) 
    @ResponseBody 
    public ResponseEntity<String> exceptionHandler(Exception e) { 
     return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST); 
    } 
} 
+0

我仍然得到相同的JSON响应(请参阅我的问题的底部)而不是'“出错了”' – sargas

+0

@ ControllerAdvice'是控制器的一个方面。你的AJAX调用甚至没有得到控制器 - 从响应我猜你没有在'/ bad_enpoint'控制器上执行POST(或根本没有控制器) –

+0

我有一个定义端点的@ RestController类。应该在同一个类上注释@RestController和@ControllerAdvice? – sargas