본문 바로가기

express

The process error handling

1. Occured some Error.

ex. inputed ungettable type of object or bad request

2. If we let the error be/ if we dont do anything with this error, the server is shut donwed.

so we need to controll or handle errors.

3. Catch errers ! use "try { } catch { }" or anything we can.

I made some middleware to catch err and connect with handler

const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

module.exports = asyncHandler;

and putted this to all of the methods, then we can catch any occured error.

4. After catching error, do some appropricate response

like, telling the clients what is wrong with your input or what is wrong in this system now depends on type of errors.

5. To respone to clients. we need to make response object. this is ErrorResponse.

class ErrorResponse extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;

    Error.captureStackTrace(this, this.constructor);
  }
}

module.exports = ErrorResponse;

this object create ErrorResponse depends on message and statusCode

6. Next, using ErrorResponse.

define errorHandler. depends on what kinds of error occured. and then response with this error.

const ErrorResponse = require('../utils/errorResponse');

const errorHandler = (err, req, res, next) => {
  let error = { ...err };

  error.message = err.message;

  // Log to console for dev
  console.log(err);

  // Mongoose bad ObjectId
  if (err.name === 'CastError') {
    const message = `Resource not found`;
    error = new ErrorResponse(message, 404);
  }

  // Mongoose duplicate key
  if (err.code === 11000) {
    const message = 'Duplicate field value entered';
    error = new ErrorResponse(message, 400);
  }

  // Mongoose validation error
  if (err.name === 'ValidationError') {
    const message = Object.values(err.errors).map(val => val.message);
    error = new ErrorResponse(message, 400);
  }

  res.status(error.statusCode || 500).json({
    success: false,
    error: error.message || 'Server Error'
  });
};

module.exports = errorHandler;

'express' 카테고리의 다른 글

Udemy course spec/APIs  (0) 2020.05.13
How to manage of 1:N relationship? mongoose  (0) 2020.05.12
회원 가입  (0) 2020.05.03
express api 분석 1."dependencies"  (0) 2020.05.01
Thinkster node.js API 강의 후기.  (0) 2020.05.01