2014-04-30 1 views
1

배열에 여러 변수가 섞여 있고 그 중 일부 변수가 일반 또는 사용자 정의 오류 일 수 있습니다 (예 : var v = new Error() 또는 var v = new MyCustomError()으로 생성).변수가 자바 스크립트에서 오류인지 어떻게 결정합니까?

오류 인스턴스를 다른 변수와 구별하는 일반적인 방법이 있습니까? 감사.

편집 : 사용자 지정 오류가 형식에 : 당신은, 대부분의 instanceof 연산자를 사용할 수 있습니다

function FacebookApiException(res) { this.name = "FacebookApiException"; this.message = JSON.stringify(res || {}); this.response = res; } FacebookApiException.prototype = Error.prototype;

+1

'instanceof'가 처리합니다. – alex

+0

우리에게 'MyCustomError'를 보여줄 수 있습니까? – Bergi

+0

@ Evan 질문에 추가하십시오. –

답변

2

, 예를 들어,

var err = new Error(); 
if (err instanceof Error) { 
    alert('That was an error!'); 
} 

이 부분은 jsfiddle입니다. 객체의 프로토 타입 체인에 constructor.prototype의

instanceof 운영자 테스트 존재 :

모질라 개발자 네트워크 (MDN)는 것을 알리는 instanceof 운영자 here에 대한 자세한 내용을 가지고 있습니다.

같은, 당신이 출력이 의견에 반영 얻을 것이다 다음 입력 주어진 :

function C(){} // defining a constructor 
function D(){} // defining another constructor 

var o = new C(); 
o instanceof C; // true, because: Object.getPrototypeOf(o) === C.prototype 
o instanceof D; // false, because D.prototype is nowhere in o's prototype chain 
o instanceof Object; // true, because: 
C.prototype instanceof Object // true 

C.prototype = {}; 
var o2 = new C(); 
o2 instanceof C; // true 
o instanceof C; // false, because C.prototype is nowhere in o's prototype chain anymore 

D.prototype = new C(); // use inheritance 
var o3 = new D(); 
o3 instanceof D; // true 
o3 instanceof C; // true 
+0

숀 퀸 (Sean Quinn)과 모든 코멘트 작성자에게 감사 드리며 완벽하게 작동합니다. –

+0

답안의 두 번째 부분은 중요합니다 : * [[Prototype]] 체인이 변경되지 않았으며 그 객체가 다중 생성자의 "인스턴스"가 될 수 있다면 * instanceof *는 정상입니다. – RobG

3

이 같은 오류에서 제대로 상속하지 않는 FacebookApiException, 내가 뭘 제안 일 :

function FacebookApiException(res) { 
    //re use Error constructor 
    Error.call(this,JSON.stringify(res || {})); 
    this.name = "FacebookApiException"; 
    this.response = res; 
} 
//Faceb... is an Error but Error is not Faceb... 
// so you can't set it's prototype to be equal to Error 
FacebookApiException.prototype = Object.create(Error.prototype); 
//for completeness, not strictly needed but prototype.constructor 
// is there automatically and should point to the right constructor 
// re assigning the prototype has it pointing to Error but should be 
// FacebookApiException 
FacebookApiException.prototype.constructor = FacebookApiException; 
+0

매우 흥미 롭습니다. 지적 해 주셔서 감사합니다! Object.create()를 발견하게되어 정말 기쁩니다. –

+0

OP는'FacebookApiException.prototype = new Error()'를 수행하고 * 생성자 * 속성을 재설정 할 수도 있지만 위의 방법이 더 좋습니다. – RobG