簡體   English   中英

AngularJS-Spring MVC Rest:如何處理異常

[英]Angularjs - Spring MVC Rest : how to handle exceptions

我正在使用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類。 如果有人在這里看到我錯了...

謝謝

您可以使ExceptionHandlerMessagingException並設置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時幾乎相同。

通過kTT回答,從Spring 4開始,您可以將@ExceptionHandler方法包裝在帶有@ControllerAdvice注釋的類中,以便在整個應用程序中針對相同類型的異常具有相同的消息。 更多你可以看這里

這就是我做到的方式,我們在項目中使用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;
}

然后在RESTful控制器中,其中ServiceException是自定義的可運行異常:

@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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM