2016-03-19 12 views
1

我想創建自己的異常。 所以我可以根據nodejs服務器運行的環境來格式化錯誤。當錯誤被拋出時,這是未定義的。自定義異常。這個undefined

(function() { 
    'use strict'; 
    var states = require('../states'); 
    var env = states.config.env; 
    var _ = require('underscore'); 

    /** 
    * This is a error that is going to be thrown on server errors. 
    * The application format the message for the specific environment 
    * @param error The error 
    */ 
    var unrecoverableError = function (error) { 
    this.name = 'unrecoverableError'; 
    this.message = _.isEqual(env, 'production') ? 'There was a server error. Please contact server admin' : error.toString(); 
    this.code = 500; 
    }; 

    unrecoverableError.prototype = Object.create(Error.prototype); 
    unrecoverableError.prototype.constructor = unrecoverableError; 

    module.exports = unrecoverableError; 
}()); 

我也使用sequelize作爲ORM。

organisation.findOne({ 
     where: { 
      name: organisationName 
     } 
     }) 
     .then(function (organisation) { 
      if (_.isEmpty(organisation)) { 
      throw new modelNotFoundException(); 
      } else { 
      resolve(organisation); 
      } 
     }) 
     .catch(function (error) { 
      if (error instanceof modelNotFoundException) { 
      reject(error); 
      } else { 
      throw new unrecoverableError(error); 
      } 
     }) 
     .catch(function (error) { 
      reject(error); 
     }); 

然後在我的控制檯中出現錯誤。

[類型錯誤:無法設置的未定義的屬性「名」]

我想不出我做錯了什麼。它在瀏覽器中工作。 這是一個工作小提琴的例子。 https://jsfiddle.net/y3gk0hos/

在此先感謝

回答

1

發生錯誤的原因是"use strict";聲明防止全球環境的「非法」進入的存在。

如果在沒有new關鍵字的情況下調用功能unrecoverableError,則this對象將指向全局環境。雖然在瀏覽器中允許,但'use strict';聲明不允許這樣做。

爲了保證unrecoverableError方法實例化一個對象,你需要檢查它是否被執行,而不new關鍵字和強制正確使用:

var unrecoverableError = function (error) { 
    // check if called with 'new' 
    if (this instanceof unrecoverableError) { 
    this.name = 'unrecoverableError'; 
    this.message = 'There was a server error. Please contact server admin'; 
    this.code = 500; 
    } 
    else { 
    // method was not called with 'new' 
    return new unrecoverableError(error); 
    } 
}; 
+1

我打電話給新的權利?或者我理解你錯了。 「拋出新的不可恢復的錯誤(錯誤);」 –

+0

該解決方案的工作原理,但我不知道這是否是正確的解決方案。 –

1

我不明白爲什麼它的重要,只顯示錯誤消息在production環境中。

下面是在Node中創建自定義錯誤所需遵循的一些代碼:https://gist.github.com/justmoon/15511f92e5216fa2624b因此重構以匹配該格式。

但是,這似乎可能是比它的價值更多的工作。你大概可以這樣做:throw new Error('Unrecoverable: ' + e.message)

+0

因爲我使用自定義錯誤來顯示響應。所以一個modelNotFoundException會給出一個404.而且我得到了一個給出400的invalidParamsException。並且所有的錯誤都將是一個不可恢復的錯誤。該消息被回覆給用戶。所以我不希望系統錯誤顯示給用戶。因爲它的系統錯誤對用戶來說太沒用了 –

+0

如果你想使用自定義錯誤,但是我正在討論prod/vs dev的檢查,那麼在這個例子中,好像它只是在控制檯顯示消息dev/test以及prod。但這是一個側面問題。 –

+0

你可以嘗試改變你的代碼看起來更像是鏈接的要點嗎? –