Error plugin
A plugin for Merkur is tiny extensible javascript library for front-end microservices.
@merkur/plugin-error adds semi-automatic error handling to your Merkur widget:
- Return a custom HTTP status based on thrown error
- Render valid JSON with error code and message
- Render an error page
- Run arbitrary code on error (e.g. to log/report the error)
- Catch unhandled promise errors
- Provide error class to extend
Installation
src/widget.js
Install plugin:
import { errorPlugin } from '@merkur/plugin-error';
//...
widgetProperties = {
name,
version,
$plugins: [
//...
errorPlugin, // keep error plugin as last plugin in array
],
View,
//...
src/router/widgetAPI/widgetAPI.js
Set HTTP status in widget API response:
//...
.get(
'/widget',
//...
// optional chaining & nullish coalescing operator
const status = info?.error?.status ?? 200;
res.status(status).json({ ...info, html });
src/router/playground/playground.js
To allow widget playground to display the widget in error state, add playground error-handling middleware after playground route.
//...
const { playgroundErrorMiddleware } = require('@merkur/plugin-error/server');
// ...
const router = express.Router();
const containerSelector = '.container';
router
.get(
'/',
asyncMiddleware(async (req, res) => {
// ....
res
.status(200)
.send(playgroundTemplate({ widgetProperties, html, containerSelector }));
})
)
.use(playgroundErrorMiddleware({ renderPlayground: playgroundTemplate, containerSelector }))
Operation
When an error is thrown, the plugin does the following:
- saves the error status and message on the widget object:
widget.error = { status: error.status || 500, message: error.message }
- emit
ERROR
event with thrown error - Re-runs the function (if defined)
The error object is available everywhere in the widget, as well as to the host application.
Limitations
The plugin can’t handle errors occurring outside of lifecycle functions.
## Custom errors
You can throw custom errors by instantiating GenericError
class or create custom error classes that extend GenericError
.
GenericError
class carries status
param among with other params. This way error plugin can respond with adequate HTTP status and also include data for encountered error.
import { GenericError } from '@merkur/plugin-error';
throw new GenericError('Operation failed.', {
status: 500,
reason: 'api_error'
})