LoginSignup
3
0

More than 3 years have passed since last update.

NestJS デフォルトの例外まとめ built-in exception

Last updated at Posted at 2021-04-08

built-in exception

NestJSはベースとなるHttpExceptionを継承するいくつかのよく使う例外をデフォルトで提供している。
何が用意されていて、ステータスコードがどれでとか調べるのが面倒なのでまとめた。

exception response body
BadRequestException { "statusCode": 400, "message": "Bad Request" }
UnauthorizedException { "statusCode": 401, "message": "Unauthorized" }
ForbiddenException { "statusCode": 403, "message": "Forbidden" }
NotFoundException { "statusCode": 404, "message": "Not Found" }
MethodNotAllowedException { "statusCode": 405, "message": "Method Not Allowed" }
NotAcceptableException { "statusCode": 406, "message": "Not Acceptable" }
RequestTimeoutException { "statusCode": 408, "message": "Request Timeout" }
ConflictException { "statusCode": 409, "message": "Conflict" }
GoneException { "statusCode": 410, "message": "Gone" }
PreconditionFailedException { "statusCode": 412, "message": "Precondition Failed" }
PayloadTooLargeException { "statusCode": 413, "message": "Payload Too Large" }
UnsupportedMediaTypeException { "statusCode": 415, "message": "Unsupported Media Type" }
ImATeapotException { "statusCode": 418, "message": "I'm a teapot" }
MisdirectedException { "statusCode": 421, "message": "Misdirected" }
UnprocessableEntityException { "statusCode": 422, "message": "Unprocessable Entity" }
InternalServerErrorException { "statusCode": 500, "message": "Internal Server Error" }
NotImplementedException { "statusCode": 501, "message": "Not Implemented" }
BadGatewayException { "statusCode": 502, "message": "Bad Gateway" }
ServiceUnavailableException { "statusCode": 503, "message": "Service Unavailable" }
GatewayTimeoutException { "statusCode": 504, "message": "Gateway Timeout" }
HttpVersionNotSupportedException { "statusCode": 505, "message": "HTTP Version Not Supported"

使い方

引数なし

import { BadGatewayException } from @nestjs/common

throw new BadGatewayException()
{
  "statusCode": 502,
  "message": "Bad Gateway"
}

message変更

引数に文字列を入れるとmessageとして挿入され、デフォルトのmessageerrorとして返される

import { BadGatewayException } from @nestjs/common

throw new BadGatewayException("error message!!")
{
  "statusCode": 502,
  "message": "error message!!",
  "error": "Bad Gateway"
}

await-catch使うとこんな感じ

import { BadGatewayException } from @nestjs/common

async () => {
  await test().catch(e => throw new BadGatewayException(e.message)
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0