Support throw-style errors + auto get port

This commit is contained in:
rijkvanzanten
2020-06-16 14:14:12 -04:00
parent 76dae3caad
commit 536d4f7c49
6 changed files with 72 additions and 9 deletions

View File

@@ -1,5 +1,14 @@
import express from "express";
import express from 'express';
import asyncHandler from 'express-async-handler';
import APIError, { errorHandler, ErrorCode } from './error';
const app = express();
const app = express()
.get(
'/',
asyncHandler(async (req, res, next) => {
throw new APIError(ErrorCode.NOT_FOUND, 'Route `/` not found');
})
)
.use(errorHandler);
export default app;

39
src/error.ts Normal file
View File

@@ -0,0 +1,39 @@
import { ErrorRequestHandler } from 'express';
export enum ErrorCode {
NOT_FOUND = 'NOT_FOUND',
}
enum HTTPStatus {
NOT_FOUND = 404,
}
export const errorHandler: ErrorRequestHandler = (error: APIError, req, res, next) => {
res.status(error.status);
const response: any = {
error: {
code: error.code,
message: error.message,
},
};
if ((process.env.NODE_ENV = 'development')) {
response.error.stack = error.stack;
}
res.json(response);
};
export default class APIError extends Error {
status: HTTPStatus;
code: ErrorCode;
constructor(code: ErrorCode, message: string) {
super(message);
this.status = HTTPStatus[code] || 500;
this.code = code;
Error.captureStackTrace(this, this.constructor);
}
}

View File

@@ -1,8 +1,11 @@
import app from "./app";
import logger from "./logger";
import app from './app';
import logger from './logger';
import getPort from 'get-port';
const port = process.env.PORT || 3000;
(async () => {
const port = process.env.PORT || (await getPort({ port: 3000 }));
app.listen(port, () => {
logger.info(`Server started at port ${port}`);
});
app.listen(port, () => {
logger.info(`Server started at port ${port}`);
});
})();