LAD和KOA的更好的錯誤處理程序。使
ctx.throw很棒(與KOA-404 Handler一起使用)
ETIMEOUT和EBADFAMILY ),並發送408客戶端超時錯誤<ul>支持HTML錯誤列表,用於蒙古驗證錯誤,多個消息ctx.throw直接美麗的消息(例如ctx.throw(404)將輸出一個美麗的錯誤對象)text/html , application/json和text響應類型npm install --save koa-better-error-handler您可能也應該將其與KOA-404 Handler結合使用!
該軟件包導出一個接受四個參數的函數(按順序):
cookiesKey默認為falselogger默認為consoleuseCtxLogger默認為truestringify默認為fast-safe-stringify (您還可以在此處使用JSON.stringify或其他選項(如果首選))如果您通過cookiesKey ,則將添加對會話的支持。如果使用cookie和會話(例如Web服務器),則應始終設置此參數的值。
我們建議將機艙用於logger ,您也應該使用其中間件,因為它將自動填充ctx.logger ,以使您的基於上下文的日誌變得容易。
請注意,此軟件包僅支持koa-generic-session ,並且尚未支持koa-session-store (請參閱index.js中的代碼以獲取更多洞察力,歡迎拉動請求)。
不支持會議,cookie或Flash消息傳遞:
const errorHandler = require ( 'koa-better-error-handler' ) ;
const Koa = require ( 'koa' ) ;
const Router = require ( 'koa-router' ) ;
const koa404Handler = require ( 'koa-404-handler' ) ;
// initialize our app
const app = new Koa ( ) ;
// override koa's undocumented error handler
app . context . onerror = errorHandler ( ) ;
// specify that this is our api
app . context . api = true ;
// use koa-404-handler
app . use ( koa404Handler ) ;
// set up some routes
const router = new Router ( ) ;
// throw an error anywhere you want!
router . get ( '/404' , ctx => ctx . throw ( 404 ) ) ;
router . get ( '/500' , ctx => ctx . throw ( 500 ) ) ;
// initialize routes on the app
app . use ( router . routes ( ) ) ;
// start the server
app . listen ( 3000 ) ;
console . log ( 'listening on port 3000' ) ;對會話,cookie和Flash消息的內置支持:
const errorHandler = require ( 'koa-better-error-handler' ) ;
const Koa = require ( 'koa' ) ;
const redis = require ( 'redis' ) ;
const RedisStore = require ( 'koa-redis' ) ;
const session = require ( 'koa-generic-session' ) ;
const flash = require ( 'koa-connect-flash' ) ;
const convert = require ( 'koa-convert' ) ;
const Router = require ( 'koa-router' ) ;
const koa404Handler = require ( 'koa-404-handler' ) ;
// initialize our app
const app = new Koa ( ) ;
// define keys used for signing cookies
app . keys = [ 'foo' , 'bar' ] ;
// initialize redis store
const redisClient = redis . createClient ( ) ;
redisClient . on ( 'connect' , ( ) => app . emit ( 'log' , 'info' , 'redis connected' ) ) ;
redisClient . on ( 'error' , err => app . emit ( 'error' , err ) ) ;
// define our storage
const redisStore = new RedisStore ( {
client : redisClient
} ) ;
// add sessions to our app
const cookiesKey = 'lad.sid' ;
app . use (
convert (
session ( {
key : cookiesKey ,
store : redisStore
} )
)
) ;
// add support for flash messages (e.g. `req.flash('error', 'Oops!')`)
app . use ( convert ( flash ( ) ) ) ;
// override koa's undocumented error handler
app . context . onerror = errorHandler ( cookiesKey ) ;
// use koa-404-handler
app . use ( koa404Handler ) ;
// set up some routes
const router = new Router ( ) ;
// throw an error anywhere you want!
router . get ( '/404' , ctx => ctx . throw ( 404 ) ) ;
router . get ( '/500' , ctx => ctx . throw ( 500 ) ) ;
// initialize routes on the app
app . use ( router . routes ( ) ) ;
// start the server
app . listen ( 3000 ) ;
console . log ( 'listening on port 3000' ) ; 示例請求:
curl -H " Accept: application/json " http://localhost/some-page-does-not-exist示例響應:
{
"statusCode" : 404 ,
"error" : " Not Found " ,
"message" : " Not Found "
}截至v3.0.5,您可以通過設置no_translate的錯誤屬性以具有true的值來防止錯誤自動翻譯:
function middleware ( ctx ) {
const err = Boom . badRequest ( 'Uh oh!' ) ;
err . no_translate = true ; // <----
ctx . throw ( err ) ;
} 如果指定app.context.api = true或設置ctx.api = true ,並且發生貓鼬驗證錯誤消息,該消息發生多個消息(例如,多個字段無效),則err.message將由逗號遵守,而不是<li> 。
因此,如果您確實希望您的API錯誤消息返回HTML格式的錯誤列表以進行Mongoose驗證,則設置app.context.api = false , ctx.api = false ,或者只是在使用此錯誤處理程序之前只確保不設置它們。
try {
// trigger manual validation
// (this allows us to have a 400 error code instead of 500)
await company . validate ( ) ;
} catch ( err ) {
ctx . throw ( Boom . badRequest ( err ) ) ;
}帶有錯誤列表:
{
"statusCode" : 400 ,
"error" : " Bad Request " ,
"message" : " <ul class= " text-left mb-0 " ><li>Path `company_logo` is required.</li><li>Gig description must be 100-300 characters.</li></ul> "
}沒有錯誤列表:
{
"statusCode" : 400 ,
"error" : " Bad Request " ,
"message" : " Path `company_logo` is required., Gig description must be 100-300 characters. "
}默認情況下,如果ctx.api為真,則將在err.message上調用html-to-Text,從而將所有HTML標記轉換為文本格式。
您還可以在環境中指定一個基本URI,以呈現為process.env.ERROR_HANDLER_BASE_URL ,例如ERROR_HANDLER_BASE_URL=https://example.com (省略落後slash slash),以及任何html鏈接,如<a href="/foo/bar/baz">Click here</a> [1] [Click here][1]鏈接附加https://example.com/foo/bar/baz 。
麻省理工學院©Nick Baugh