自定义错误

exception/http.exception.js

  1. class HttpException extends Error{
  2. constructor(status,message,errors){
  3. super()
  4. this.status = status
  5. this.message = message
  6. this.errors = errors
  7. }
  8. }
  9. module.exports = HttpException

常见状态码分类 1xx : 通知 2××:请求成功地接收 3××:重定向问题 4××:客户错误 5××:服务器错误

状态码 ① 200:请求成功,浏览器会把响应体内容(通常是html)显示在浏览器中;
② 404:(客户端问题)请求的资源没有找到,说明客户端错误的请求了不存在的资源;
③ 500:(服务端问题)请求资源找到了,但服务器内部发生了不可预期的错误;


统一错误处理

  1. const errorMiddleware = (error,req,res,next)=>{
  2. console.log(error);
  3. const status = error.status || 500;
  4. const message = error.message || '服务器端错误'
  5. const errors= error.errors || '服务器端错误'
  6. res
  7. .status(status)
  8. .json({
  9. code:0,
  10. message:message,
  11. errors:errors
  12. })
  13. }
  14. module.exports = errorMiddleware

重构404中间件

  1. const HttpException = require('../exception/http.exception')
  2. const noMatchMiddleware = (req,res,next)=>{
  3. const noMatchError = new HttpException(404,'访问路径不匹配','router url not found')
  4. next(noMatchError)
  5. }
  6. module.exports = noMatchMiddleware

测试错误捕获