mirror of
https://github.com/directus/directus.git
synced 2026-02-08 07:24:59 -05:00
Support throw-style errors + auto get port
This commit is contained in:
13
src/app.ts
13
src/app.ts
@@ -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
39
src/error.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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}`);
|
||||
});
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user