mongoose 에러 핸들링

Tesseractjh

·

2022. 4. 3. 23:43

Built-in Validator

export const UserSchema = new Schema(
  {
    userId: {
      type: String,
      unique: true,
      required: true,
      match: /[a-z0-9_]{4,16}/,
    },
   
    ...
    
  }
);

mongoose Schema를 작성할 때, 각각의 field에 대해 validator를 지정할 수 있으며, 각각의 validator를 통과하지 못하면 에러를 발생시킨다.

아이디를 입력하지 않은 경우 (required validator에서 오류 발생)

이 때 Path `userId` is required가 오류 메시지이며, 이 오류 메시지를 Array Syntax로 간단하게 커스텀할 수 있다.

export const UserSchema = new Schema(
  {
    userId: {
      type: String,
      unique: true,
      required: [true, '아이디를 입력하세요.'],
      match: [
        /[a-z0-9_]{4,16}/,
        '아이디는 4 ~ 16자의 영문 소문자, 숫자, _ 조합으로 입력해야 합니다.'
      ]
    },
   
    ...
    
  }
);

위와 같이 각 validator의 값을 배열의 형태로 validator 값과 에러메시지를 작성할 수 있다.

 

export const ProductSchema = new Schema(
  {
    categories: {
      type: [
        {
          type: String,
          enum: {
            values: ['원두', '생두', '싱글오리진', '블렌드', '디카페인', '콜드브루'],
            message: '카테고리가 유효하지 않습니다.'
          }
        }
      ],
      required: [true, '카테고리를 입력하세요.']
    },
   
    ...
    
  }
);

enum의 경우 Object Syntax로 작성해야 정상적으로 동작한다.

 

unique는 validator가 아니다

unique는 validator가 아니기 때문에 위와 같은 형식으로 커스텀 에러메시지를 작성할 수 없다.

이 경우에는 에러 객체의 name과 code로 중복으로 인한 에러 여부를 판별해야 한다.

if (err.name === 'MongoServerError' && err.code === 11000) {
  ...
}

 

type의 경우도 마찬가지로 커스텀 에러메시지를 작성할 수 없기 때문에, 에러 name으로 타입으로 인한 에러 여부를 판별해야 한다.

if (err.name === 'CastError') {
  ...
}

 

에러 객체의 errors 프로퍼티

mongoose의 에러 객체에는 errors 프로퍼티가 있으며, 이 객체 안에 발생한 모든 에러의 정보가 담겨 있다.

위에서 작성한 커스텀 메시지는 errors에 있는 객체의 message 프로퍼티에 담기게 된다.

다른 정보 말고 이 커스텀 메시지만을 얻기 위해서 아래와 같이 코드를 작성하였다.

const message = Object
  .values(err.errors)
  .map((error) => error.message);

이렇게 해서 API 요청시 발생한 모든 에러의 원인을 message에 담아 클라이언트로 응답을 보내도록 하였다.

 

참고자료

https://my-codinglog.tistory.com/13

 

[Node.js] error handling, custom error message 등

팀프로젝트 중 사용자 인증, 허가 부분 백엔드 부분을 작성하게 되었는데, 비정상적인 입력 등 뭔가 예외적인 사항들을 프론트에서 처리하는 것인지 백엔드에서 처리하는 것인지 잘 몰라서 예

my-codinglog.tistory.com

https://stackoverflow.com/questions/38945608/custom-error-messages-with-mongoose

 

Custom Error Messages with Mongoose

So according to the mongoose docs, you are supposed to be able to set a custom error message in the schema like so: var breakfastSchema = new Schema({ eggs: { type: Number, min: [6, 'To...

stackoverflow.com

https://stackoverflow.com/questions/63402084/how-can-i-get-specific-error-messages-from-a-mongoose-schema

 

How can i get specific error messages from a Mongoose Schema?

I am trying to set up user validation in Mongoose and struggling to get the specific messages to appear. Here is my model const userSchema = new Schema({ name: { type: String,

stackoverflow.com