1
+ function showError ( ) {
2
+ throw new Error ( "Error en la aplicación" ) ;
3
+ }
4
+
5
+ function iniciarApp ( ) {
6
+ try {
7
+ showError ( ) ;
8
+ } catch ( error ) {
9
+ console . error ( `${ error } ` ) ;
10
+ } finally {
11
+ console . log ( "Aplicación finalizada\n" )
12
+ }
13
+ }
14
+
15
+ iniciarApp ( ) ;
16
+
17
+ //EXTRA
18
+ interface errorSuma {
19
+ errorCode :number ,
20
+ body :string
21
+ }
22
+ console . log ( "**************MANEJO DE ERRORES*************" )
23
+ export abstract class CustomError extends Error {
24
+ abstract errorCode : number ;
25
+
26
+ constructor ( message : string ) {
27
+ super ( message ) ;
28
+ Object . setPrototypeOf ( this , new . target . prototype ) ;
29
+ }
30
+ }
31
+
32
+ export class ValidationError extends CustomError {
33
+ errorCode = 0 ;
34
+ constructor ( message :string ) {
35
+ super ( message ) ;
36
+ this . name = "ValidationError"
37
+ }
38
+ }
39
+ export class OutOfRange extends CustomError {
40
+ errorCode = - 1 ;
41
+ constructor ( message :string ) {
42
+ super ( message ) ;
43
+ this . name = "OutOfRange"
44
+ }
45
+ }
46
+
47
+ export default function handleError ( error : unknown ) : errorSuma {
48
+ if ( error instanceof CustomError ) {
49
+ return {
50
+ errorCode : error . errorCode ,
51
+ body : JSON . stringify ( { message : error . message } ) ,
52
+ } ;
53
+ } else {
54
+ return {
55
+ errorCode : 500 ,
56
+ body : JSON . stringify ( { error } ) ,
57
+ } ;
58
+ }
59
+ }
60
+
61
+ function app ( numero :number ) {
62
+ try {
63
+ switch ( numero ) {
64
+ case 1 :
65
+ throw new ValidationError ( "Validación incorrecta, inténtalo de nuevo" ) ;
66
+ case 2 :
67
+ throw new OutOfRange ( "El número esta fuera del rango permitido" ) ;
68
+ case 3 :
69
+ let list :string [ ] = [ "hola" ] ;
70
+ let data :number = list [ 2 ] . length
71
+ console . log ( data ) ;
72
+ break ;
73
+ default :
74
+ console . dir ( "No se ha producido ningún error" )
75
+ break ;
76
+ }
77
+ } catch ( error ) {
78
+ const response = handleError ( error ) ;
79
+ console . warn ( "Código de error: " + response . errorCode )
80
+ if ( response . errorCode <= 0 ) {
81
+ console . error ( `ERROR: ${ response . errorCode } , ${ response . body } ` ) ;
82
+ } else {
83
+ console . error ( `ERROR: ${ error } ` ) ;
84
+ }
85
+ } finally {
86
+ console . log ( "Aplicación finalizada\n" ) ;
87
+ }
88
+ }
89
+
90
+ app ( 1 ) ;
91
+ app ( 2 ) ;
92
+ app ( 3 ) ;
93
+ app ( 4 ) ;
0 commit comments