簡體   English   中英

Spring MVC @ControllerAdvice異常行為因異常源而異

[英]Spring MVC @ControllerAdvice exception behavior different based on Exception source

取決於是通過對NamedParameterJdbcTemplate的調用(即jdbcTemplate.update(sql,namedParameter))的調用引發了DuplicateKeyException(DKE),還是由我在代碼中明確引發的,行為是完全不同的。

當jdbcTemplate調用引發DKE時,將發生正確的行為。 我的@ControllerAdvice啟動,並返回正確的HTTP狀態和ResponseBody。 但是,當我顯式拋出DKE時,即使看到@ControllerAdvice類中的正確代碼塊,也將向客戶端返回500錯誤。

這是處理異常的代碼,該異常應始終返回HttpStatus.OK和RestError:

@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody RestError handleDuplicateKey(
    HttpServletRequest request, Exception ex) {     

    logger.error("GlobalExceptionHandler handling exception of type DuplicateKeyException.class: ", ex);
    return new RestError(HttpStatus.CONFLICT, 
                     ErrorCode.DUPLICATE_ENTRY, 
                     ex.getCause().getMessage());
    }

這是可以引發DKE的代碼:

public void insertSubscriber(SubscriberInfo subscriberInfo) {

    if (isAlreadySubscribed(subscriberInfo)) {
        // this will result in a 500 http error to the client
        throw new DuplicateKeyException(
            String.format("This subscriber is already subscribed");
    }

    String sql = "INSERT INTO subscribers (firstname, email, postal_code, subscriber_type) "
               + "VALUES (:firstname, :email, :postal_code, :subscriber_type)";

    HashMap<String, String> namedParameter = Maps.newHashMapWithExpectedSize(4);
    namedParameter.put("email", subscriberInfo.getEmail());
    namedParameter.put("postal_code", subscriberInfo.getPostalCode());
    namedParameter.put("subscriber_type", subscriberInfo.getUserType().getId());
    namedParameter.put("firstname", subscriberInfo.getFirstname());

    // if a DKE is thrown from the below line, everything works fine. 
    jdbcTemplate.update(sql, namedParameter);       
}

我真的很想了解為什么行為會根據異常的來源而有所不同。

我猜您只是在DKE中設置了味精,而在異常處理程序中,您正在執行ex.getCause()。getMessage(),我想這是在拋出NPE。 嘗試使用味精設置可拋出原因,然后嘗試一下。

暫無
暫無

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

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