【发布时间】:2015-12-10 16:12:28
【问题描述】:
在 Angular JS web 应用程序中,如果我的 rest API 返回异常(未处理的抛出),我如何向前端显示适当的错误。
目前我只能显示一般错误“创建记录时出错”。但无法从异常中检索到确切的错误消息
控制器
$http.post("/mdmservice/services/entity", $scope.entity).success(function(data, status, headers, config, statusText) {
$scope.created=true;
$scope.buttonsDisabled = true;
$scope.entityCreatedMessage = "New record created successfully.";
$scope.error=false;
}).error(function(data, status, headers, config, statusText ) {
console.log("Error creating entity : " +data +"," +status +"," +headers +"," +config +"," +statusText);
$scope.error=true;
$scope.errorMessage="Error creating record.";
});
REST API
@POST
@Path(value = "/create")
@Consumes(value = MediaType.APPLICATION_JSON)
@Override
public Long create(Eentity entity) {
Long entityId = null;
entity.setEntityId(null);
entity.setIsExcluded("N");
try {
// For create, the editIndicator=1
entityId = entityBusiness.createOrUpdate(entity, 1);
} catch (Exception e) {
throw new WebApplicationException(e);
}
return entityId;
}
异常日志
Caused by: com.jay.MyException: Entity code must be unique
at com.jay.BusinessImpl.createOrUpdateEntity(EntityBusinessImpl.java:93)
at com.jay.service.impl.EntityServiceImpl.createEntity(EntityServiceImpl.java:145)
... 38 more
Caused by: com.jay.common.exception.EbaDataException: Entity code must be unique
at com.jay.mdm.data.repository.jdbc.impl.EntityRepositoryJdbcImpl.createOrUpdateEntity(EntityRepositoryJdbcImpl.java:304)
at com.jay.mdm.business.impl.EntityBusinessImpl.createOrUpdateEntity(EntityBusinessImpl.java:91)
... 39 more
<Dec 10, 2015 4:08:54 PM GMT> <Warning> <org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper> <BEA-000000> <javax.ws.rs.WebApplicationException: H
TTP 500 Internal Server Error
【问题讨论】:
-
您可以通过
data访问success和error的服务器响应。$scope.entityCreatedMessage = data; -
@user3632710 谢谢,但错误消息作为异常抛出,无法在控制器中获取这些消息。你的意思是我们永远不会抛出异常而是捕获它并在返回的对象中返回一条消息?
-
我经常使用express而不是java,所以我真的帮不上你。也许stackoverflow.com/questions/30863177/…这个问题和你的有关?