天天看點

自定義Exception異常初體驗

使用場景:删除檢查項,先在資料庫中查詢該項有沒有被添加到檢查組,若查詢到已被添加,則傳回這個自定義的異常

自定義異常:
package com.jacob.entity;

public class CheckItemDeleteException extends Exception{
    public CheckItemDeleteException() {
    }

    public CheckItemDeleteException(String message) {
        super(message);
    }
}
           
檢查項service impl,檢查項服務接口實作類      
//删除檢查項,先查詢要删除的檢查項有沒有被添加到檢查組
    public void delete(String itemId) throws CheckItemDeleteException {
        int countCheckItem = checkItemDao.countCheckItem(itemId);
        if (countCheckItem!=0){ 
                //Add exception to method signature,直接在方法抛出異常,交給上層處理
            throw new CheckItemDeleteException("該項已被添加到檢查組");
        }else{
            checkItemDao.delete(itemId);
        }
    }
           
不能這樣:這樣異常抛不到上層
//删除檢查項,先查詢要删除的檢查項有沒有被添加到檢查組
    public void delete(String itemId)  {
        int countCheckItem = checkItemDao.countCheckItem(itemId);
        if (countCheckItem!=0){
            try {
                throw new CheckItemDeleteException("該項已被添加到檢查組");
            } catch (CheckItemDeleteException e) {
                e.printStackTrace();
            }
        }else{
            checkItemDao.delete(itemId);
        }
    }
           
Controller層,可以定位出發生了什麼異常,而不是簡單的傳回删除失敗
@RequestMapping("/delete")
    /* @RequestBody主要用來接收前端傳遞給後端的json字元串中的資料的(請求體中的資料的);
     */
    public Result delete(String itemId){
        try {
            checkItemService.delete(itemId);
        } catch (Exception e) {
            if(e instanceof CheckItemDeleteException){
                return new Result(false,"該項已被添加到檢查組");
            }
            return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }
           

繼續閱讀