package com.inductiveautomation.opcua.stack.core.channel;

import com.inductiveautomation.opcua.stack.core.StatusCodes;
import com.inductiveautomation.opcua.stack.core.UaException;
import com.inductiveautomation.opcua.stack.core.UaRuntimeException;
import com.inductiveautomation.opcua.stack.core.channel.messages.ErrorMessage;
import com.inductiveautomation.opcua.stack.core.channel.messages.TcpMessageEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class ExceptionHandler {

    public static ErrorMessage sendErrorMessage(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String message = cause.toString();
        long statusCode = StatusCodes.Bad_UnexpectedError;

        Throwable innerCause = cause.getCause();

        if (innerCause instanceof UaException) {
            UaException ex = (UaException) innerCause;
            message = ex.getMessage();
            statusCode = ex.getStatusCode().getValue();
        } else if (innerCause instanceof UaRuntimeException) {
            UaRuntimeException ex = (UaRuntimeException) innerCause;
            message = ex.getMessage();
            statusCode = ex.getStatusCode();
        }

        ErrorMessage error = new ErrorMessage(statusCode, message);
        ByteBuf messageBuffer = TcpMessageEncoder.encode(error);

        ctx.writeAndFlush(messageBuffer).addListener(future -> ctx.close());

        return error;
    }

}

@@ -664,16 +664,18 @@
 use.
-toString
+getMessage
 ();%0A
@@ -734,16 +734,226 @@
 Error;%0A%0A
+        if (cause instanceof UaException) %7B%0A            UaException ex = (UaException) cause;%0A            message = ex.getMessage();%0A            statusCode = ex.getStatusCode().getValue();%0A        %7D else %7B%0A    
         
@@ -998,24 +998,28 @@
 );%0A%0A        
+    
 if (innerCau
@@ -1051,32 +1051,36 @@
 ) %7B%0A            
+  
+  
 UaException ex =
@@ -1110,32 +1110,36 @@
 se;%0A            
+    
 message = ex.get
@@ -1153,32 +1153,36 @@
 ();%0A            
+  
+  
 statusCode = ex.
@@ -1201,32 +1201,36 @@
 e().getValue();%0A
+    
         %7D else i
@@ -1288,16 +1288,20 @@
         
+  
+  
 UaRuntim
@@ -1353,32 +1353,36 @@
 se;%0A            
+    
 message = ex.get
@@ -1396,32 +1396,36 @@
 ();%0A            
+  
+  
 statusCode = ex.
@@ -1437,24 +1437,38 @@
 atusCode();%0A
+            %7D%0A
         %7D%0A%0A 

Refactor ExceptionHandler logic