directory

I will continue to update several articles in the future. The specific catalog is as follows

  1. Egg gracefully implements exception handling
  2. Egg implements JWT authentication

preface

These articles are for taking notes. Keep them short and practical. Suppose eggJS develops an API interface server, and returns the correct JSON format according to various situations, and gracefully implements exception handling;

Why do you need error handling

  1. Prevent the program from hanging
  2. Tell the user the error message
  3. Convenient development and debugging, locating problems
  4. API interface server specified return data structure

Several kinds of errors

  1. Program run error such as error 500
  2. Develop the exception errors you throw
  3. 404 error

Implement middleware yourself

Let’s start by implementing middleware ourselves to handle errors, and the next topic is how to avoid building wheels

module.exports = options= > {
  return async(ctx, next) => {
    try {
      await next();
    } catch (err) {
    // We will simply try catch the exception, exactly because the first program mentioned above runs with no status or statusCode, because there are 500 handlers
      ctx.status = err.status || err.statusCode || 500;
      ctx.body = {
        message: err.message,
      }
    }
  }
}
Copy the code

This is a simple custom error middleware that allows us to implement error handling similar to the one shown below (here we throw 403 in controller via koA’s own ctx.throw method).

However, there is a small problem with this middleware, which is not friendly to 404 and does not return JSON as required

Avoid reinventing the wheel

Egg is based on KOA, we don’t have to duplicate the wheel here, we can use a good wheel from the community koa-JSON-err; You can click on the link to read more at Github

Koa middleware is used in Egg

// middlware/error.js
module.exports = require('koa-json-error');
Copy the code
Config.middleware = ['error']; // config/config.xxx.js config.middleware = ['error']; Config. error = {// Appinfo.env is used to determine the environment, only in non-production environment to open the stack information, used for debugging postFormat: (e, {stack,... rest}) => appInfo.env === 'prod' ? rest: { stack, ... rest} }Copy the code

conclusion

This is a brief introduction to the elegant handling of exceptions in an Egg; The next article will briefly cover how to implement JWT certification