@@ -178,27 +178,46 @@ private void StartBasicConsume()
178178 {
179179 if ( _consumerChannel != null )
180180 {
181- var consumer = new EventingBasicConsumer ( _consumerChannel ) ;
182- consumer . Received += async ( model , ea ) =>
183- {
184- var eventName = ea . RoutingKey ;
185- var message = Encoding . UTF8 . GetString ( ea . Body ) ;
186-
187- await ProcessEvent ( eventName , message ) ;
181+ var consumer = new AsyncEventingBasicConsumer ( _consumerChannel ) ;
188182
189- _consumerChannel . BasicAck ( ea . DeliveryTag , multiple : false ) ;
190- } ;
183+ consumer . Received += Consumer_Received ;
191184
192- _consumerChannel . BasicConsume ( queue : _queueName ,
193- autoAck : false ,
194- consumer : consumer ) ;
185+ _consumerChannel . BasicConsume (
186+ queue : _queueName ,
187+ autoAck : false ,
188+ consumer : consumer ) ;
195189 }
196190 else
197191 {
198- _logger . LogError ( "StartBasicConsume can not call on _consumerChannelCreated == false " ) ;
192+ _logger . LogError ( "StartBasicConsume can't call on _consumerChannel == null " ) ;
199193 }
200194 }
201195
196+ private async Task Consumer_Received ( object sender , BasicDeliverEventArgs eventArgs )
197+ {
198+ var eventName = eventArgs . RoutingKey ;
199+ var message = Encoding . UTF8 . GetString ( eventArgs . Body ) ;
200+
201+ try
202+ {
203+ if ( message . ToLowerInvariant ( ) . Contains ( "throw-fake-exception" ) )
204+ {
205+ throw new InvalidOperationException ( $ "Fake exception requested: \" { message } \" ") ;
206+ }
207+
208+ await ProcessEvent ( eventName , message ) ;
209+ }
210+ catch ( Exception ex )
211+ {
212+ _logger . LogWarning ( ex , "----- ERROR Processing message \" {Message}\" " , message ) ;
213+ }
214+
215+ // Even on exception we take the message off the queue.
216+ // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX).
217+ // For more information see: https://www.rabbitmq.com/dlx.html
218+ _consumerChannel . BasicAck ( eventArgs . DeliveryTag , multiple : false ) ;
219+ }
220+
202221 private IModel CreateConsumerChannel ( )
203222 {
204223 if ( ! _persistentConnection . IsConnected )
@@ -209,7 +228,7 @@ private IModel CreateConsumerChannel()
209228 var channel = _persistentConnection . CreateModel ( ) ;
210229
211230 channel . ExchangeDeclare ( exchange : BROKER_NAME ,
212- type : "direct" ) ;
231+ type : "direct" ) ;
213232
214233 channel . QueueDeclare ( queue : _queueName ,
215234 durable : true ,
0 commit comments