2014-08-28 4 views
2

이 내 Node.js를 서버가내부 서버 API 및 HTTP API

organisation

문제 어떻게 구성되어 있는지입니다 사이의 오류 처리 방법 : API 모델을 통해 내 MongoDB를 데이터베이스에 대한 요청을 만드는을 (몽구스). 그래서 API 계층에서 내가 가질 수

User.findById(id, function(user) { 
    if(user._id !== userid) return deferred.reject(new Error()); // ?? 
    if(!user) return deferred.reject(new Error()); // ?? 
    user[field] = value; 
    user.save(function() { 
    deferred.resolve(user); 
    }); 
}); 

하지만 어떤 오류가 발생 하는가? 어떤 방법으로보다 적절하고 사용자에게 친숙해질 수 있습니다. 내가 예를 들어 시도 할 수 :

if(user._id !== userid) return deferred.reject(new Error(403)); 

하지만 그건 어떤 메시지를 의미하지 않을 것이다, 단지 오류 코드 :/

내가 시도 또 다른 해결책 :

exports.errors = errors = 

    NOT_FOUND: 
    id: "NOT_FOUND" 
    code: 404 
    message: "Can't found requested object. Please retry" 
    UNAUTHORIZED: 
    id: "UNAUTHORIZED" 
    code: 401 
    message: "Please login first" 
    FORBIDDEN: 
    id: "FORBIDDEN" 
    code: 403 
    message: "Access denied." 
    DATABASE_ERROR: 
    id: "DATABASE_ERROR" 
    code: 500 
    message: "Error with databse. Please retry" 

exports.throwError = throwError = (message, id) -> 
    if typeof message is "string" then err = new Error message else err = message 
    err.type = id 
    err.data = errors[id] 
    return err 

exports.handleHttp = (err, req, res, format="text") -> 
    console.log(" Error - #{err.message} (#{err.type}) on #{req.url}".red) 
    console.log(err.stack) 
    if format is "text" 
    res.send err.data.code, "#{err.data.type}: #{err.message}" 
    if format is "json" 
    res.send err.data.code, 
     type: err.data.type 
     message: err.message 
     id: err.type 
     status: "error" 
     errors: err.errors 

그래서 내가 그 같이 사용할 것 :

if(user._id !== userid) return deferred.reject(error.throwError("Forbidden", "UNAUTHORIZED")); 

그리고 (약속 후) 컨트롤러

.fail (err)-> 
    errors.handleHttp err, req, res, "json" 

하지만이 솔루션이 마음에 들지 않아 불만을 토로합니다. 다른 생각?

답변

2

기존 Error 객체를 확장하는 새로운 Error 객체를 정의 할 수 있습니다. 예를 들어, 다음은 404 오류에 대한 것 :

function HttpError(message, code) { 
    this.message = message || ""; 
    this.code = code || 500; 
} 

HttpError.prototype = Object.create(Error.prototype); 

HttpError.prototype.send = function send(req, res) { 
    var type = req.accepts("json", "html", "text"); 

    switch(type) { 
     case "json": 
      res.send(this.code, JSON.stringify(this)); 
     break; 

     case "html": 
     case "text": 
      res.send(this.code, "An error occurred: " + this.message); 
     break; 
    } 
}; 

function NotFoundError(message, code) { 
    this.name = "NotFound"; 
    this.message = message || "Could not find the object you were requesting"; 
    this.code = code || 404; 
} 
NotFoundError.prototype = Object.create(HttpError.prototype); 

당신은 다음과 같이 사용할 수 있습니다 :

User.findById(id, function(user) { 
    if(!user) return deferred.reject(new NotFoundError()); 

    user[field] = value; 
    user.save(function() { 
    deferred.resolve(user); 
    }); 
}); 

당신은 오류 (500, 404, 401 등을 모두 배치 할 수 있습니다)를 오류 파일에 넣고 포함시킵니다. 그래서 가능성이 new errors.NotFoundError();

그런 다음, 컨트롤러에 당신이 실패 콜백 기능과 같이 할 수있을 것입니다 : ERR가 HttpError 클래스의 인스턴스 인 경우에만 작동합니다

getUser().fail(function(err) { err.send(req, res) }); 

.

+0

감사합니다. 컨트롤러에 대한 처리 방법은 무엇입니까? – Vinz243

+0

컨트롤러 로직으로 업데이트되었습니다. 원래 정의한 것과 매우 유사하게 처리 할 수 ​​있습니다. –

+1

대단히 감사합니다! 아마도 다른 것을 추가 할 수 있습니다 proto에 그 기능을 처리하는 함수? – Vinz243