An open API service indexing awesome lists of open source software.

https://github.com/koajs/error

Error response middleware (text, json, html)
https://github.com/koajs/error

Last synced: about 2 months ago
JSON representation

Error response middleware (text, json, html)

Awesome Lists containing this project

README

        

# koa-error

Error response middleware for koa supporting:

- [x] text
- [x] json
- [x] html

## Installation

```bash
# npm
$ npm install koa-error
# yarn
$ yarn add koa-error
```

## Options

- `template` path to template written with your template engine, default: `./error.html`
- `engine` template engine name passed to [consolidate](https://github.com/ladjs/consolidate), default: `lodash`
- `cache` cached compiled functions, default: `NODE_ENV != 'development'`
- `env` force a NODE_ENV, default: `development`
- `accepts` mimetypes passed to [ctx.accepts](https://github.com/koajs/koa/blob/master/docs/api/request.md#requestacceptstypes), default: `[ 'html', 'text', 'json' ]`

## Custom templates

By using the `template` option you can override the bland default template,
with the following available local variables:

- `env`
- `ctx`
- `request`
- `response`
- `error`
- `stack`
- `status`
- `code`

Here are some examples:

### Pug (formerly jade)

```js
app.use(
error({
engine: "pug",
template: __dirname + "/error.pug",
})
);
```

```jade
doctype html
html
head
title= 'Error - ' + status
body
#error
h1 Error
p Looks like something broke!
if env == 'development'
h2 Message:
pre: code= error
h2 Stack:
pre: code= stack
```

### Nunjucks

```js
app.use(
error({
engine: "nunjucks",
template: __dirname + "/error.njk",
})
);
```

```html


Error - {{status}}



Error


Looks like something broke!


{% if env == 'development' %}

Message:




{{error}}


Stack:




{{stack}}


{% endif %}

```

#### Custom filters, use macro,block in Nunjucks

koa-error engine tool base on [consolidate](https://github.com/ladjs/consolidate), you can also set consolidate options

> [more-nunjucks-options](https://github.com/ladjs/consolidate/blob/master/lib/consolidate.js#L1436-L1488) > `app.js`:

```js
//...
const app = new Koa();
const nunjucks = require("nunjucks");
const nunjucksEnv = new nunjucks.Environment(
new nunjucks.FileSystemLoader(path.join(__dirname, "tpl"))
);

// add filters
const filters = require("./filters");
for (let [k, v] of Object.entries(filters)) {
nunjucksEnv.addFilter(k, v);
}

//...
app.use(
koaError({
//...
template: path.join(__dirname, "tpl/error.html"),
options: {
nunjucksEnv, // custom nunjucks env
},
})
);
```

`filters.js`:

```js
module.exports = {
// define filters function here
stringify(..args){
return JSON.stringify(...args);
}
//...
};
```

`tpl/error.html`:

```html


{% include "./com.html" %}


{{ request | stringify }}

{# use filters here #}

```

`tpl/com.html`:

```html

```

## License

[MIT](LICENSE)