我有一个连接到数据库的RESTful Web应用程序,它具有正常的REST,业务逻辑服务和持久层。什么是在RESTful层中处理运行时错误(如数据库连接不可用)的JAX-RS标准方法?我相信下面的方法,我用Throwable的try / catch包装对服务/持久层的任何调用,并抛出我的自定义MyAppRuntimeException有点尴尬。有什么建议吗?
RESTful服务:
@Path("service")
@Consumes({"application/json"})
@Produces({"application/json"})
public class MyResource {
@GET
@Path("/{id}")
public Response getPage(@PathParam("id") long id){
Object test=null;
try {
test = ...
//call business logic service method here which makes a call to database and populates test instance
} catch (Throwable e) {
throw new MyAppRuntimeException("custom error message string");
}
if(test != null){
return Response.ok(test).build();
}else{
return Response.status(Status.NOT_FOUND).build();
}
}
}
自定义例外:
public class MyAppRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MyAppRuntimeException(String message) {
super(message);
}
public MyAppRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
异常JAX-RS响应映射器:
@Provider
public class MyAppRuntimeExceptionMapper implements ExceptionMapper<MyAppRuntimeException> {
private static final String ERROR_KEY = "DATA_ERROR";
@Override
public Response toResponse(MyAppRuntimeException exception) {
ErrorMessage errorMessage = new ErrorMessage(ERROR_KEY, exception.getMessage(), null);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorMessageDTO).build();
}
}
答案 0 :(得分:2)
让你的异常类扩展WebApplicationException
并将它扔到任何你喜欢的地方。您可以在下面的示例中看到,您可以以任何必要的方式自定义响应。快乐的编码!
注意:此示例处理403
错误,但您可以轻松创建处理500
,503
等的异常。
package my.package.name;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.Serializable;
public class Http401NotAuthorizedException extends WebApplicationException implements Serializable {
private static final long serialVersionUID = 1L;
public Http401NotAuthorizedException(String msg){
super(
Response
.status(Response.Status.FORBIDDEN)
.header("Pragma", "no-cache, no-store")
.header("Cache-Control", "no-cache, no-store")
.header("Expires", "0")
.entity(msg)
.build()
);
}
}