Error Handling : Status Code

Judy·2023년 1월 26일
0

In RESTful API

HTTP = URL(URI) + HTTP method + Status Code

Showing here, popular status code example of response

Status Code in Layered Pattern

Controller

  • http request, http response
  • Handle verification, error, exception when data flows User → FrondEnd → BackEnd
  • Most representative error : KEY_ERROR (400)
  • When user input is wrong, most of them 400

Example

  • Key Error : 400
    • If user didn’t input key value (email…)

      const { email, password } = req.body
      
      console.log(email)    // ''
      console.log(password) // 'myPassword''
      
      if (!email) {
          const err = new Error('KEY_ERROR')
          err.statusCode = 400;
          throw err
      }
  • Read(Review / Return) value : 200
    const readCart = asyncErrorHandler(async (req, res) => {
      cartList = await cartService.readCart(req.userId);
      return res.status(200).json(cartList);
    });
  • Delete : 204
    const deleteCart = asyncErrorHandler(async (req, res) => {
      const { cartId } = req.params;
    
      await cartService.deleteCart(cartId);
      return res.status(204).json({
        message: "DELETE_CART_SUCCESS",
      });
    });

Service

  • Business logic (rule)
  • Exceptions and errors intended by developer (follows business logic (rule))
  • Error can occur on-
    • the layer under service layer
    • service module that called directly on service layer
  • User request error : 400
  • BackEnd(DB) error : 500

Example

  • Conflict : 409
    • Response status code indicates a request conflict with the current state of the target resource.

    • If user password doesn’t follow password creating rule

      const signUp = async (name, email, password, profileImage) => {
          const pwValidation = new RegExp(
            '^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,20})'
          );
          if (!pwValidation.test(password)) {
              const err = new Error('PASSWORD_IS_NOT_VALID');
              err.statusCode = 409;
              throw err;
          }

Dao

  • Database Error
  • Other external systems are interlocked (different from Node, Express)
  • At this point, asynchronous calls are mainly used. ⇒ We should use suitable method for asynchronous error handling

Example

  • BackEnd(DB) error : 500
    const createUser = async ( name, email, password, profileImage ) => {
        try {
            return await myDataSource.query(
            `INSERT INTO users(
                name,
                email,
                profile_image,
                password
            ) VALUES (?, ?, ?, ?);
            `,
            [ name, email, password, profileImage ]
          );
        }
        catch (err) {
        const err = new Error('INVALID_DATA_INPUT');
        err.statusCode = 500;
        throw err;
        }
profile
NLP Researcher

0개의 댓글