2013-10-18 76 views
1

我有一個包裝RESTful API的Node模塊。此客戶端遵循標準的節點回調格局:在Express路由中處理錯誤

module.exports = { 
    GetCustomer = function(id, callback) { ...} 
} 

我打電話從不同的快遞路線這個客戶,像這樣:

app.get('/customer/:customerId', function(req,res) { 
MyClient.GetCustomer(customerId, function(err,data) { 
    if(err === "ConnectionError") { 
    res.send(503); 
    } 
    if(err === "Unauthorized") { 
    res.send(401); 
    } 
    else { 
    res.json(200, data); 
    } 
    }; 
}; 

的問題是,我認爲這是不幹燥,檢查「ConnectionError」每次我打電話給這個客戶。我不相信我可以撥打res.next(err),因爲這會發回500錯誤。

是否有節點或Javascript模式我在這裏丟失?在C#或Java中,我會在MyClient中引發適當的異常。

+0

如果您註冊一個什麼自定義錯誤處理程序中間件? – gustavohenke

回答

2

您想創建錯誤處理中間件。下面是快速的例子:https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

這是我使用:

module.exports = function(app) { 

    app.use(function(req, res) { 
    // curl https://localhost:4000/notfound -vk 
    // curl https://localhost:4000/notfound -vkH "Accept: application/json" 
    res.status(404); 

    if (req.accepts('html')) { 
     res.render('error/404', { title:'404: Page not found', error: '404: Page not found', url: req.url }); 
     return; 
    } 

    if (req.accepts('json')) { 
     res.send({ title: '404: Page not found', error: '404: Page not found', url: req.url }); 
    } 
    }); 

    app.use(function(err, req, res, next) { 
    // curl https://localhost:4000/error/403 -vk 
    // curl https://localhost:4000/error/403 -vkH "Accept: application/json" 
    var statusCode = err.status || 500; 
    var statusText = ''; 
    var errorDetail = (process.env.NODE_ENV === 'production') ? 'Sorry about this error' : err.stack; 

    switch (statusCode) { 
    case 400: 
     statusText = 'Bad Request'; 
     break; 
    case 401: 
     statusText = 'Unauthorized'; 
     break; 
    case 403: 
     statusText = 'Forbidden'; 
     break; 
    case 500: 
     statusText = 'Internal Server Error'; 
     break; 
    } 

    res.status(statusCode); 

    if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { 
     console.log(errorDetail); 
    } 

    if (req.accepts('html')) { 
     res.render('error/500', { title: statusCode + ': ' + statusText, error: errorDetail, url: req.url }); 
     return; 
    } 

    if (req.accepts('json')) { 
     res.send({ title: statusCode + ': ' + statusText, error: errorDetail, url: req.url }); 
    } 
    }); 
}; 
相關問題