본문 바로가기

express

What should I do with Errors? express.js

What should I do with errors?

When we make a server API, there gonna be error everywhere.

For these errors, what should I do?

Just don't let the server be shut downed. this is all we need.

How? Catch errors and Response with that.

 

1. We can response to error types that are already exist in JS or js frameworks.

InternalError

: Creaet an instance representing an error that occurs when an internal error in the JS engine is thrown. E.g "too mach recursion".

RangeError

:Creates an instance representing an error that occurs when a numeric vairable or parameter is outside of its valid range.

ReferenceError

: Create an instance representing an error that occurs when de-referencing an invalid referennce.

SystaxError

: Create an instance representing a syntax error.

TypeError

: Create an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError

: Create an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalide parameters.

and so on.. These are JS Error("https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Examples")

 

2. We can create CustomError types and use it.

We might want to define our own error types deriving from Error to be able to throw new MyError().

Create CustomError below

class MyCustomError extends Error {
  constructor(message) {
    super(message);
    this.message = message;
    this.name = 'MyError';
  }
}

We can use customError, for each Errors occured in runtime. example below

const MyCustomError = require('myCustomError');

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 fount`;
    error = new MyCustomError(message);
  }
  
  // Mongoose duplicate key
  if (err.code === 11000) {
    const message = 'Dulicate field value entered';
    error = new MyCustomError(message);
  }
  
  res.json({
    success: false,
    error: error.message
  });
};

module.exports = errorHandler;

Or we can use customError lightly. Specially when we make controllers

If there is some work that needs permission, and if users donsn't have permission. the app should return error. in this case we can use customError lightly.

exports.deleteCourse = async (req, res, next) => {
  const course = await Course.findById(req.params.id);
  
  if (course.user.role !== 'admin') {
    return next(
      new MyCustomError(`User ${req.user.id} is not authorized to delete this course`);
    );
  }
      

Just pass customError to next() function. that is all we need.

'express' 카테고리의 다른 글

So what do I do with Token?  (0) 2020.05.19
TOKEN authentication  (0) 2020.05.19
Error Handling using Promise.  (0) 2020.05.16
How does HTTP request looks like  (0) 2020.05.15
How do I do object CRUD?  (0) 2020.05.15