Spring Boot端点中的异常处理

时间:2017-04-18 21:35:15

标签: java spring spring-mvc spring-boot exception-handling

我正在尝试在具有SOAP端点和Rest控制器的spring启动应用程序中处理异常。

捕获其余控制器中发生的异常非常简单,我只是使用@extrolleradvice设置了一个具有@exceptionhandler方法的类,并且捕获了所有异常。但是,这个controlleradvice似乎没有捕获SOAP端点中发生的异常。有没有办法捕获@controlleradvice类中端点中抛出的异常?如果没有,是否有其他方法可以在整个应用程序中集中异常处理,而不是抛出异常的位置?

提前非常感谢你。

1 个答案:

答案 0 :(得分:0)

我们可以创建自定义例外:

@ResponseStatus(HttpStatus.NOT_FOUND) public class StudentNotFoundException extends 
RuntimeException {}

Spring中的异常处理程序:

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends 
ResponseEntityExceptionHandler {
@ExceptionHandler(StudentNotFoundException.class)
 public final ResponseEntity<ErrorDetails> 
 handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {
  ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
  request.getDescription(false));
 return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}


public class ErrorDetails {
private Date timestamp;
private String message;
private String details;

public ErrorDetails(Date timestamp, String message, String details) {
  super();
 this.timestamp = timestamp;
  this.message = message;
  this.details = details;
 }