(Node.js)express制御HTTPステータスコードからエラーへ


throw new Error('BadRequest')
javascriptでエラーを投げ出すのは簡単で実行しやすい方法です.
expressでもそうです.エラーが投げ出されると、200 OKではなく500個の内部サービスエラーが発生する可能性があります.
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  throw new Error('BadRequest');
});
app.listen(3000, () => {
  console.log('listen');
});
http-errorの使用
const express = require('express');
const createError = require('http-errors');
const app = express();

app.get('/', (req, res) => {
  throw new createError.BadRequest();
});
app.listen(3000, () => { console.log('listen') });
希望するエラーコードを挿入http-errorsと書くよりも、勒類を直接表現したいのかもしれません.
エラーオブジェクトに必要なステータスコードをstatusまたはstatusCodeで入れます.
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  const e = new Error('sample');
  e.status = 400;
  throw e;
});
app.listen(3000, () => { console.log('listen') });
ライブラリから投げ出されるエラーの制御
ErrorにstatusとstatusCodeを入れるのはJavaScriptワールドの標準ではありません.そのため、多くのライブラリのエラークラスにはstatus、statusCodeプロパティがありません.
サンプルライブラリyup/ValidationError
export default function ValidationError(errors, value, field, type) {
  this.name = 'ValidationError';
  this.value = value;
  this.path = field;
  this.type = type;
  this.errors = [];
  this.inner = [];
  // ...
  this.message =
    this.errors.length > 1
      ? `${this.errors.length} errors occurred`
      : this.errors[0];

  if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
}
上記のライブラリを使用する場合、エラーが投げ出された場合、どのように対応しますか?
方法は、catchによってライブラリから投げ出されたエラーをキャプチャし、http-errorsに戻すことです.しかし、既存のコードをすべてcatchで包むのは無謀だ.
expressミドルウェアの使用
エラー処理プログラムでは、err.nameをチェックし、必要なエラーを投げ出すように処理することができる.
const express = require('express');
const createErrors = require('http-errors');
const jwt = require('jsonwebtoken');
const app = express();

app.get('/', (req, res) => {
  throw new jwt.JsonWebTokenError('this is sample error');
});

const newErrorMap = new Map([
  ['JsonWebTokenError', createErrors.BadRequest],
  ['ValidationError', createErrors.BadRequest],
]);

app.use((err, req, res, next) => {
  const newError = newErrorMap.get(err.name);
  if (newError) {
    next(new newError(err.message));
  } else {
    next(err);
  }
});

app.listen(3000, () => { console.log('listen'); });