JavaScript: 오류, 유형, 속성

이 블로그에서, 나는 자바스크립트의 오류 유형을 토론할 것이다.앉아서 팝콘을 준비하세요.
Javascript 실행 중 오류 던지기, 오늘 코드에서 이 오류를 읽고, 이해하고, 사용하는 방법을 볼 수 있습니다

오류:
JS에서 오류는 객체입니다.그것은 하나의 클래스Error가 있고 구조 함수Error()가 있다.이것은 JS에서 통용되는 오류 클래스입니다.
여러 종류의 오류가 있습니다. 이것은 여러 종류의 오류가 있다는 것을 의미합니다.
그래서 우리는 이러한 구조 함수에서 오류 대상을 만들 수 있다.
범용 구조 함수 오류는 인자를 포함합니다. (오류 메시지를 설명하는 데 사용됩니다.)
//as Error is an object we can create it from its class' constructor
let newError = new Error("MyMessage for the error");
//now this newError is an instance(object) of class Error
그래, 네가 옳다. 만약 그것이 대상이고, 클래스가 있다면, 그것도 속성이 있어야 한다.
잘못된 객체의 표준 속성:

1. 이름-
기본적으로 오류 인스턴스의 이름은 "Error"입니다.클래스 Error의 모든 인스턴스에는 "Error"라는 속성이 있습니다.

2. 메시지 -
메시지 속성은 오류에 대한 읽을 수 있는 설명입니다.오류가 포함된 간략한 정보입니다.

3.toString-
너는 아마도 우리도 대상의 토스트링 방법이 있다고 생각할 것이다.그러나 오류 객체는 해당 객체를 덮어씁니다.원형toString().
백엔드에서 이름과 메시지를 조합해서 문자열로 변환합니다.
이것은 3개의 표준 속성이고 다른 비표준 속성도 있지만 일부 브라우저에서는 지원하지 않을 수도 있습니다.
아래의 예를 보여 주시오
console.log(newError)
Uncaught Error: MyMessage for the error
    at <anonymous>:1:13
상기 오류의 첫 번째 단어인 Uncaught 을 참고하십시오. 이것은catch 키워드로 오류를 처리하지 않았다는 것을 의미합니다.
다음 단어는 - Error: 잘못된name 속성의 값입니다.
다음 부분은 - MyMessage for the error: 오류 메시지의 속성 값입니다.
다음 부분은-at <anonymous>:1:13: 이것은 매우 중요한 부분이다. 이것은 창고 추적으로 오류가 발생한 위치를 표시하고 블로그의 뒷부분에서 상세하게 토론할 것이다.
그래서 위의 문장은 잘못된 모든 속성이다.
toString():
toString 메서드는 오류가 발생할 때 호출되며 -name:message와 유사한 문자열을 반환합니다.
이름 속성 값이 정의되지 않은 경우 이름 값이 Error인 문자열을 반환합니다.
메시지 속성 값이 정의되지 않은 경우 메시지 값이 빈 문자열인\"\"을 반환합니다.
우리는 toString () 방법의 예시를 볼 것이다.
var error1 = new Error('Bad operation');
console.log(error1.name) //Error 
//As it is an instance of Error class
console.log(error1.message) //Bad operation
console.log(error1.toString()); // 'Error: Bad operation'

var error2 = new Error('Bad operation');
error2.name = undefined;
//assigned undefined to error2 name property
console.log(error2.toString()); // 'Error: Bad operation'
//toString will return "Error" for undefined name

var error3 = new Error('Bad operation');
error3.name = 'hello';
error3.message = undefined;
//assigned undefined to error3 message property
console.log(error3.toString()); // 'hello'
//toString will return empty string for undefined message
JavaScript에는 범용 오류 구조 함수 외에 다른 핵심 오류 구조 함수도 있습니다.우리는 이 블로그에서 그 중의 일부 내용을 배울 것이다.

1. 범위 오류:
값이 허용되는 값의 컬렉션이나 범위 내에 있지 않으면 RangeError 객체가 던져집니다.
구조 함수: RangeError()
속성:
  • 메시지: RangeError는 자신의 메시지 속성을 제공해야 한다
  • 이름: 기본적으로 RangeError name 속성의 값은 "RangeError"입니다.
    이 두 속성은 모두 오류 클래스에서 계승된 것이다
  • function checkAge(n)
    {
        try{
            if( !(n >= 18) )
            {
                throw new RangeError("Age must be greater than 18 to sign up")
            }
        }catch(error) { 
             console.error(error);
        }
    }
    checkAge(13)
    // RangeError: Age must be greater than 18 to sign up
    // at checkAge (<anonymous>:6:19)
    // at <anonymous>:1:1
    
    

    2. 참조 오류:
    코드에서 존재하지 않는 변수를 참조하거나 사용하면 ReferenceError 객체가 발생합니다.
    구조 함수: ReferenceError()
    속성:
  • 메시지: ReferenceError는 자신의 메시지 속성을 제공해야 합니다
  • 이름: 기본적으로 ReferenceError name 속성의 값은 "ReferenceError"입니다.
    이 두 속성은 모두 오류 클래스에서 계승된 것이다
  • let name="Ankita"
    function printFullName( ) {
        try{
             console.log(`${name} ${surname}`);
        } catch( error ){
             console.error(error)
        }
    }
    printFullName( );
    //ReferenceError: surname is not defined
    //  at printFullName (<anonymous>:4:33)
    //  at <anonymous>:9:1
    

    3.SyntaxError:
    프로그램에 잘못된 구문 코드가 있으면 Syntax Error 객체가 제거됩니다.
    구조 함수: SyntaxError()
    속성:
  • 메시지: SyntaxError는 자신의 메시지 속성을 제공해야 합니다
  • name: 기본적으로 SyntaxError name 속성의 값은 "SyntaxError"입니다.
    이 두 속성은 모두 오류 클래스에서 계승된 것이다
  • const printName = (){
        console.log("Ankita");
    }
    //Above arrow function has fat arrow missing, it will throw below error
    //Uncaught SyntaxError: Unexpected token ')'
    

    4. 타자 오류:
    작업을 수행할 수 없을 때 TypeError 객체는 값이 예상한 유형이 아닐 때 주로 던져집니다.
    구조 함수: TypeError()
    속성:
  • 메시지: TypeError는 자신의 메시지 속성을 제공해야 한다
  • 이름: 기본적으로 TypeError name 속성의 값은 "TypeError"입니다.
    이 두 속성은 모두 오류 클래스에서 계승된 것이다
  • // This is 1st kind of TypeError, where we try to change a value that cannot be changed
    const marks = 200;
    const totalMarks = 250;
    marks = marks * 100 / totalMarks;
    //Uncaught TypeError: Assignment to constant variable.
    //   at <anonymous>:1:7
    
    //This is 2nd kind of TypeError. If an operand/argument is passed to a operator/function whose type is not compatible with the operator/function.
    //below code tries to apply spread operator on a number, hence it throws an TypeError
    let number = 9;
    let numberSpreaded = [...number];
    // Uncaught TypeError: number is not iterable
    //   at <anonymous>:1:26
    
    
    //This is 3rd kind of TypeError, when a value is used in an inappropriate way
    //below reduce method can be called on array, but instead we are calling it on a number, it will throw an TypeError
    let arr= 9;
    arr.reduce((sum,num)=>sum+num, 0);
    // Uncaught TypeError: arr.reduce is not a function
    //    at <anonymous>:2:5
    

    5. 오류:
    전역 URI 방법을 잘못 사용하면 URIerror가 발생합니다.
    e, g.decodeURI() 함수는 인코딩된 URI를 매개 변수로 사용하며, 인코딩된 URI에 잘못된 문자 시퀀스가 포함된 경우 URIerror를 내보냅니다.
    구조 함수: URIerror()
    속성:
  • 메시지: URIError는 자신의 메시지 속성을 제공해야 한다
  • 이름: 기본적으로 URIerror name 속성의 값은 "URIerror"입니다.
    이 두 속성은 모두 오류 클래스에서 계승된 것이다
  • try {
      let a = decodeURI('%AN%KI%');
    } catch(e) {
      console.error(e);
    }
    //URIError: URI malformed
    //    at decodeURI (<anonymous>)
    //    at <anonymous>:2:11
    

    선택적 스냅
    예를 들어,try-catch 블록을 사용하여 오류를 처리합니다.만약 우리가 TypeError만 처리하고 문법 오류를 처리하고 싶지 않다면?
    우리는 모든 잘못이 그것들의 실례라는 것을 알고 있기 때문에 이 점을 쉽게 할 수 있다.우리는 그들의 종류를 검사하여try 블록의 오류 유형을 찾아낼 수 있다.
    function sumOfNumbersInArray (arrayOfNumbers) {
        try{
           return arrayOfNumbers.reduce((sum, num)=>sum+num, 0);
        } catch(error){
            if (error instanceof TypeError)
            console.error("Invalid type. This function works with arrays only!");
            else
            throw error
        }
    }
    sumOfNumbersInArray(3);
    // Invalid type. This function works with arrays only!
    
    function sumOfNumbersInArray (arrayOfNumbers) {
        try{
           return arrayOfNumbersss.reduce((sum, num)=>sum+num, 0);
        } catch(error){
            if (error instanceof TypeError)
            console.error("Invalid type. This function works with arrays only!");
            else
            throw error
        }
    }
    //In the above code I miss-typed the arrayOfNumbers variable, it throws an error(else block), as that error is ReferenceError and is not an instance of TypeError
    //Uncaught ReferenceError: arrayOfNumbersss is not defined
    //    at sumOfNumbersInArray (<anonymous>:3:8)
    //    at <anonymous>:1:1
    
    

    스택 추적
    이제 창고 추적에 대해 얘기해 봅시다.
    아래의 예를 고려하다.그것은 3개의 함수가 있는데, 함수 A는 B를 호출하고, 함수 B는 C를 호출한다.
    function A () {
        try{    
            console.log("I am A, I will handle the error, and invoking B");
            B();
        } catch(error){
            console.error(error);
        }
    }
    function B () {
        console.log("I am B, and invoking C");
        C();
    }
    function C (){
        console.log("I am C and I have an error");
        throw new Error("fatal error");
    }
    A();
    // I am A, I will handle the error, and invoking B
    // I am B, and invoking C
    // I am C and I have an error
    // Error: fatal error
    //    at C (<anonymous>:15:11)
    //    at B (<anonymous>:11:5)
    //    at A (<anonymous>:4:9)
    //    at <anonymous>:17:1
    
    함수 A에서 우리는 오류를 처리하지만, C에서 오류를 던진다. C에서 오류를 던지면 더 이상 실행을 멈추고, 제어는 호출점에 도달한다. 이것은 함수 B에 도달한다는 것을 의미한다. 함수 B도 실행을 멈추고, 제어는 호출점에 도달한다.이것은 함수 A에 있다는 것을 의미합니다. 현재 함수 A는catch 블록을 보았고 오류가 포착되었습니다. 현재 프로그램은 중단되지 않고 계속 실행되고 있습니다.
    현재, 이 오류는 오류 유형, 오류 메시지, 창고 추적에 대한 정보를 알려 줍니다.
    스택 추적 정보는 Stack 속성에 저장되며 디버깅 문제를 시도할 때 도움이 될 수 있습니다.그것은 우리에게 오류가 발생한 함수 이름과 어떤 함수 호출이 실패했는지 알려준다.오류가 발생했을 때 창고에 있는 모든 내용을 설명합니다.
    그래서 이것은 모두 자바스크립트에 대한 오류입니다.만약 당신이 이 블로그가 도움이 된다고 생각한다면, 평론에서 저에게 알려주세요!

    I thank my mentor Tanay Pratap who was the motivation behind this blog.


    참조 자료:
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString
  • 좋은 웹페이지 즐겨찾기