2016-08-22 63 views
1

我正在使用Node.js Express創建一些HTTP REST API。 我有打電話下劃線服務返回一個無極如下方法:Node.js Express,錯誤處理僅適用於console.error

function getAllApps(request, response) { 
    appService.getAllApps(request.query.$expand).then(function (apps) { 
      response.status(200).send(apps); 
     }) 
} 

,我映射方法如下:

var api = express.app; 
api.get('/apps', getAllApps); 

現在,我已經介紹了錯誤處理如下:

function getAllApps(request, response) { 
    appService.getApps(request.query.$expand).then(function (apps) { 
     response.status(200).send(apps); 
     }) 
     .catch(function (err) { 
      console.error('Error occurred in Apps Api: ' + err); 
      response.status(400).send(err); 
    }); 
} 

哪一個按預期工作excep牛逼是遇到錯誤時,我在控制檯中完整的錯誤堆棧如下:

Express is listening on 127.0.0.1:3000 
Web Api ready 

Error occurred in Apps Api: Error: Actions is not defined on the model. 

但我的HTTP方法的返回400和身體是空的,它僅包含大括號:

{} 
+0

你真的拋出,或者是'apps'空嗎? – Bergi

+0

'.stack'是錯誤afaik的一個非枚舉屬性,意味着它將被'send'忽略。你不希望它被髮送給用戶嗎? – Bergi

+0

@Bergi完成,道歉 – Raffaeu

回答

2

它是由不具有枚舉的屬性錯誤對象引起的,所以JSON.stringify(new Error("my message"))將返回{} 。要獲得相同的控制檯輸出,你必須coerect錯誤對象爲字符串,像這樣:

.catch(function (err) { 
    console.error('Error occurred in Apps Api: ' + err); 
    response.status(500).send("" + err); 
}); 

PS:你應該使用status(500)內部錯誤。

編輯

如果這種情況下不需要單獨的錯誤處理機制,可以讓快遞來處理你的錯誤:

function getAllApps(request, response, next) { 
    appService.getApps(request.query.$expand).then(function (apps) { 
    response.status(200).send(apps); 
    }) 
    .catch(function (err) { 
    next(err || new Error("Unknown error")); 
    }); 
} 

如果快遞默認的錯誤處理不給你滿意的結果,你可以註冊自己的錯誤處理程序:

... 

// note that the middleware having 4 parameters makes it an error handler 
app.use(function(err, req, res, next) { 
    console.error('Error occurred in Apps Api: ' + err); 
    response.status(500).send("" + err); 
}); 
+0

完美!有用 – Raffaeu

-1

取出狀態400像這樣:

function getAllApps(request, response) { 
    appService.getApps(request.query.$expand).then(function (apps) { 
    response.status(200).send(apps); 
    }) 
    .catch(function (err) { 
     console.error('Error occurred in Apps Api: ' + err); 
     response.json('Error occurred in Apps Api: ' + err); 
    }); 
} 
+1

但你的解決方案返回200,這是錯誤的REST,這是一個錯誤,所以我必須返回400或500 – Raffaeu

相關問題