我需要從 api 回傳的所有錯誤都是特定的 json 格式。因此,當我將中間件錯誤處理邏輯添加到我的 Node JS 打字稿應用程式以捕獲路由錯誤時,它不起作用。
我的 app.ts 檔案:
import express, { Application, Request, Response, NextFunction } from 'express';
import routes from './src/start/routes';
import cors from 'cors';
require('dotenv').config();
const app: Application = express();
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use('/', require('./src/routes/api.route'));
app.use('/api', routes);
//Error Handler
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
return res.status(500).json({
status: 500,
success: 0,
message: 'Error',
error: ['Server error.'],
data: {}
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`http://localhost:${PORT}`));
因此,例如,如果我輸入了錯誤的路線,我會以單個字串格式而不是我需要的 json 格式收到錯誤“Cannot GET /WrongRoute”。該怎么辦?
uj5u.com熱心網友回復:
Express 404 錯誤處理程式具有以下形式:
app.use((req, res, next) => {
res.status(404).send({msg: "404 route not found"});
});
您只需確保這是在您定義的任何路線之后。
您的四引數錯誤處理程式:
app.use((error, req, res, next) => {
// put error handling code here
});
用于不同型別的錯誤,其中特定的 Error 物件已由錯誤創建,例如路由中發生的同步例外或有人呼叫next(err). 這四個引數錯誤處理程式不會因為沒有路由匹配傳入請求而發揮作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466648.html
