如何 return 来自休息服务的错误消息
How to return error message from rest service
我用 Spring 引导定义了一个休息服务,return 是一个接口。当服务发生错误时,我如何 return 一个有意义的错误信息?结果,在浏览器上,我显示 MyInterface 类型的 Json。
下面的代码是控制器调用的服务:
public MyInterface getSomeTask() {
// business logic here
MyInterface myObject= getRelatedClass();
if(myObject == null){
// how to return error message
}
return myObject;
}
一种可能性是抛出异常,然后用 Spring 处理它,这样它 return 就可以 json。
您可能需要查看有关错误处理的 this 文章。
您可以创建将在您的逻辑中抛出然后处理它的自定义异常:
if(myObject == null){
throw new CouldNotGetRelatedClassException();
}
并且在控制器中,您可以使用如下错误处理方法:
public class FooController {
@ExceptionHandler({ CouldNotGetRelatedClassException.class})
public void handleException() {
// logic of exception handling
}
}
另一种方法可能是使用 @ControllerAdvice
注释创建 class,这将创建自定义 json 对抛出异常的响应:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
protected ResponseEntity<Object> handleNotFound(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
但是您可能想知道错误响应可能具有与您的普通对象不同的结构,因此您可能希望 return 它具有不同的 HTTP 状态代码,以便前端可以确定此消息将以不同的方式反序列化.
我用 Spring 引导定义了一个休息服务,return 是一个接口。当服务发生错误时,我如何 return 一个有意义的错误信息?结果,在浏览器上,我显示 MyInterface 类型的 Json。
下面的代码是控制器调用的服务:
public MyInterface getSomeTask() {
// business logic here
MyInterface myObject= getRelatedClass();
if(myObject == null){
// how to return error message
}
return myObject;
}
一种可能性是抛出异常,然后用 Spring 处理它,这样它 return 就可以 json。
您可能需要查看有关错误处理的 this 文章。
您可以创建将在您的逻辑中抛出然后处理它的自定义异常:
if(myObject == null){
throw new CouldNotGetRelatedClassException();
}
并且在控制器中,您可以使用如下错误处理方法:
public class FooController {
@ExceptionHandler({ CouldNotGetRelatedClassException.class})
public void handleException() {
// logic of exception handling
}
}
另一种方法可能是使用 @ControllerAdvice
注释创建 class,这将创建自定义 json 对抛出异常的响应:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {CouldNotGetRelatedClassException.class})
protected ResponseEntity<Object> handleNotFound(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
但是您可能想知道错误响应可能具有与您的普通对象不同的结构,因此您可能希望 return 它具有不同的 HTTP 状态代码,以便前端可以确定此消息将以不同的方式反序列化.