【问题标题】:Angularjs - Spring MVC Rest : how to handle exceptionsAngularjs - Spring MVC Rest:如何处理异常
【发布时间】:2015-09-01 00:16:51
【问题描述】:

我正在使用 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');
            }) 

但“原因”对象是这样的:

配置:对象数据:对象错误:“内部服务器错误”异常: “java.lang.NullPointerException”消息:“无可用消息”路径: “/api/createFichierCiel/15-00005”状态:500 时间戳:1438430232307 原型:对象头:函数(名称){状态:500 statusText: “内部服务器错误”原型:对象

所以我没有收到服务器发送的 ErrorView 类。 如果有人能在这里看到我错在哪里......

谢谢

【问题讨论】:

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


【解决方案1】:

您可以将ExceptionHandler 设为MessagingException 并设置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时几乎相同。

【讨论】:

  • 谢谢,我有点迷惑:什么是ErrorView,自定义类还是Spring类?
  • @user1260928 你的自定义类。您可以在响应对象中返回一些失败的描述,例如 ErrorView(只是我的示例)。
  • 你能多解释一下angularjs方面吗?我只是不明白什么是 MessagingService,你应该在哪里添加它,基本上什么是 get({idCommande: 1} ?
  • @Shilan MessagingService 就像我写了一个angular resource service
【解决方案2】:

添加 kTT 的答案,从 Spring 4 开始,您可以将您的 @ExceptionHandler 方法包装在一个用 @ControllerAdvice 注释的类中,这样您将获得相同类型的相同消息整个应用程序的异常。更多你可以看here

【讨论】:

    【解决方案3】:

    我就是这样做的,我们在项目中使用了 spring mvc 和 angularjs。 我有这个 controllerAdvice 类

    @ControllerAdvice
    public class ExceptionControllerAdvice {
    
    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<ErrorResponse> rulesForCustomerNotFound(HttpServletRequest req, ServiceException e) 
    {
        ErrorResponse error = new ErrorResponse();
        error.portalErrorCode = e.getExceptionCode(); 
        error.message = e.getMessage();
        return new ResponseEntity<ErrorResponse>(error, HttpStatus.NOT_FOUND);
        }
    }
    
    class ErrorResponse {
       public int portalErrorCode;
       public String message;
    }
    

    然后在 ServiceException 是自定义可运行异常的 restful 控制器中:

    @Override
    @RequestMapping("/getControls/{entity}")
    public List<Control> getControls(@PathVariable(value="entity") String entity) throws ServiceException {
        List<Control> controls = ImmutableList.of();
         try {
            controls = dao.selectControls(entity);
        } catch (Exception e) {
            logger.error("getting list of controls encountered an error ", e);
            throw new ServiceException(50, "getting list of controls encountered an error.");
        }
         return controls;
    }
    

    在我使用 angularjs 的 app.js 文件中

    .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q, $location) {
        return {
            'response': function (response) {
                //Will only be called for HTTP up to 300
                return response;
            },
            'responseError': function (rejection) {
                if(rejection.status === 0) {
                    alert('There is a problem connecting to the server. Is the server probably down?!');
                }
                else {
                    $location.url('/error').search({rejection: rejection});
                }
                return $q.reject(rejection);
            }
        };
    });
    }])
    

    并在 error.controller.js 中

    function init() {       
        ctrl.rejection = $location.search().rejection; 
        ctrl.portalErrorCode = ctrl.rejection.data.portalErrorCode;
        ctrl.errorMessage = ctrl.rejection.data.message;
        $log.info('An error occured while trying to make an ajax call' + ctrl.errorMessage + ': ' + ctrl.portalErrorCode);
    }
    

    当然还有error.tpl.html

                <h2>
                   {{ctrl.rejection.status}} {{ctrl.rejection.statusText}}
                </h2>
                <h3 class="error-details">
                    Sorry, an error has occurred!
                </h3>
                <h3 class="error-details">
                    {{ctrl.errorMessage}}
                </h3>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多