当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

koa-better-error-handler

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 索和璧
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

koa-better-error-handler

A better error-handler for Lad and Koa. Makes ctx.throw awesome (best used with koa-404-handler)

Index

Features

  • Uses Boom for making error messages beautiful (see User Friendly Responses below)
  • Simply a better error handler (doesn't remove all headers like the built-in one does)
  • Doesn't make all status codes 500 (like the built-in Koa error handler does)
  • Supports Flash messages and preservation of newly set session object
  • Fixes annoying redirect issue where flash messages were lost upon an error being thrown
  • Supports HTML Error Lists using <ul> for Mongoose validation errors with more than one message
  • Makes ctx.throw beautiful messages (e.g. ctx.throw(404) will output a beautiful error object �� )
  • Supports text/html, application/json, and text response types
  • Supports and recommends use of mongoose-beautiful-unique-validation

Install

npm install --save koa-better-error-handler

Usage

You should probably be using this in combination with koa-404-handler too!

The package exports a function which accepts four arguments (in order):

  • cookiesKey - defaults to false
  • logger - defaults to console
  • useCtxLogger - defaults to true
  • stringify - defaults to fast-safe-stringify (you can also use JSON.stringify or another option here if preferred)

If you pass a cookiesKey then support for sessions will be added. You should always set this argument's value if you are using cookies and sessions (e.g. web server).

We recommend to use Cabin for your logger and also you should use its middleware too, as it will auto-populate ctx.logger for you to make context-based logs easy.

Note that this package only supports koa-generic-session, and does not yet support koa-session-store (see the code in index.js for more insight, pull requests are welcome).

API

No support for sessions, cookies, or flash messaging:

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');

Web App

Built-in support for sessions, cookies, and flash messaging:

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');

User-Friendly Responses

Example Request:

curl -H "Accept: application/json" http://localhost/some-page-does-not-exist

Example Response:

{
  "statusCode": 404,
  "error": "Not Found",
  "message":"Not Found"
}

Prevent Errors From Being Automatically Translated

As of v3.0.5, you can prevent an error from being automatically translated by setting the error property of no_translate to have a value of true:

function middleware(ctx) {
  const err = Boom.badRequest('Uh oh!');
  err.no_translate = true; // <----
  ctx.throw(err);
}

HTML Error Lists

If you specify app.context.api = true or set ctx.api = true, and if a Mongoose validation error message occurs that has more than one message (e.g. multiple fields were invalid) – then err.message will be joined by a comma instead of by <li>.

Therefore if you DO want your API error messages to return HTML formatted error lists for Mongoose validation, then set app.context.api = false, ctx.api = false, or simply make sure to not set them before using this error handler.

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));
}

With error lists:

{
  "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>"
}

Without error lists:

{
  "statusCode":400,
  "error":"Bad Request",
  "message":"Path `company_logo` is required., Gig description must be 100-300 characters."
}

API Friendly Messages

By default if ctx.api is true, then html-to-text will be invoked upon the err.message, thus converting all the HTML markup into text format.

You can also specify a base URI in the environment variable for rendering as process.env.ERROR_HANDLER_BASE_URL, e.g. ERROR_HANDLER_BASE_URL=https://example.com (omit trailing slash), and any HTML links such as <a href="/foo/bar/baz">Click here</a> will be converted to [Click here][1] with a [1] link appended of https://example.com/foo/bar/baz.

License

MIT © Nick Baugh

  • 选项: 常用 作用 选项 改名 fields、files 是 禁用 multipart 、buffer 是 限制 maxFleldsSize-20MB、maxFileSize-200MB maxFields-1000 json jsonStrict-true、detectJSON 自定义类型 extendTypes、handler 改名: 改名很少使用,除非名字冲突,简单代码: const Koa

  • 目录 1 介绍(Introduction) 2 框架的背景(Framework backgrounds) 2.1 Express 2.2 Koa 2.3 Hapi 3 创建一个服务器(Creating a server) 3.1 Express 3.2 Koa 3.3 Hapi 4 路由控制(Routes) 4.1 Hello World 4.1.1 Express 4.1.2 Koa 4.1.3

  • export default (ctx, next) => { return next().catch((err) => { if (401 == err.status) { ctx.status = 401; ctx.body = { code: 401, msg: 'Protected resource, use Author

 相关资料
  • better-sqlite3 The fastest and simplest library for SQLite3 in Node.js. Full transaction support High performance, efficiency, and safety Easy-to-use synchronous API (better concurrency than an asynch

  • better-keyboard 是使用Javascript编写的移动端键盘组件,不支持使用rem和em做布局的项目 Options 参数 defaultResult: [] 默认值 containEl: body 父级容器 closeTitle: 完成 关闭按钮文本 max: 6 最大长度 Events 事件 onInput 点击数字按钮 onClose 键盘关闭 onClosed 关闭动画结束后

  • Better Player 是一个基于 video_player 和 Chewie 的高级视频播放器。它具有多种配置选项,解决了许多典型的用例,而且很容易运行。 Better Player 是 Chewie 中引入的理念的延续。更好的修复了常见的错误,增加了更多的配置选项并解决了典型的使用情况。 特性: 修复了常见错误 添加了高级配置选项 重构的玩家控制 播放列表支持 ListView 中的视频支

  • 该项目主要提供了用来监控 MySQL、Apache、Memcached 等服务程序的 Cacti 监控模板。

  • Ant Design Pro 是 Ant Design 官方推出的非常优秀的、开箱即用的、中台前端解决方案,而 React-Better-Admin 也是向 Ant Design Pro 学习,对标 Ant Design Pro,打造 "另一套" 优秀的、开箱即用的、中台前端解决方案。 特点 1、基于 TypeScript ������ 2、基于最新的 React 18 ������ 3、基于最流