我正在使用 angularjs 和 Spring Mcv Rest 开发单页应用程序。
我正在像 Angularjs 中那样调用我的服务(使用 javax 邮件发送邮件):SendProformaFax.get({idCommande:$scope.commande.id})
在服务器端我的服务:
@RequestMapping(value = "/sendProformaFax/{idCommande}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public void imprimeProforma(@PathVariable String idCommande) {
Commande commande = commandeRepository.findOne(new Long(idCommande));
List<Vente> ventes = venteRepository.findAllByCommande(commande);
blService.sendProformaFax(ventes);
}
我想在函数 sendProformaFax 抛出 MessagingException 时显示一条消息。
我不知道如何在我的 RestController 中返回这个异常以及如何在 Angularjs 中捕获它。
如果有人可以帮助我...
谢谢。
编辑: 在服务器端我这样做:
@ExceptionHandler(value = Exception.class)
public ErrorView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
// If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
throw e;
// Otherwise setup and send the user to a default error-view.
ErrorView mav = new ErrorView();
mav.setException(e.getMessage());
mav.setUrl(req.getRequestURL().toString());
mav.setMessage("Veuillez contacter le support informatique.");
return mav;
}
在 Angularjs 方面,我正在这样做
CreateFichierCiel.get({params:param}, function (response) {
$scope.infoMessage = "La génération du fichier CIEL est terminée."
$activityIndicator.stopAnimating();
$("#messageModal").modal('show');
$scope.find();
}, function (reason) {
$("#errorModal").modal('show');
})
但是 'reason' 对象是这样的:
config: Object data: Object error: "Internal Server Error" exception: "java.lang.NullPointerException" message: "No message available" path: "/api/createFichierCiel/15-00005" status: 500 timestamp: 1438430232307 proto: Object headers: function (name) { status: 500 statusText: "Internal Server Error" proto: Object
所以我没有收到从服务器发送的 ErrorView 类。 如果有人能看出我哪里错了...
谢谢
最佳答案
您可以为 MessagingException
创建 ExceptionHandler
并设置 HTTPStatus
以指示响应有错误(例如。BAD_REQUEST
)
@ExceptionHandler(MessagingException.class)
@ResponseStatus(HTTPStatus.BAD_REQUEST)
@ResponseBody
public ErrorView handleMessagingException(MessagingException ex) {
// do something with exception and return view
}
在 AngularJS 中,您可以像这样从资源服务中捕获它:
MessagingService.get({idCommande: 1}, function (data) {
// this is success
}, function (reason) {
// this is failure, you can check if this is a BAD_REQUEST and parse response from exception handler
};
当你使用$http
时几乎是一样的。
关于java - Angularjs - Spring MVC 休息 : how to handle exceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863177/