<p>I have a Kubernetes job running a BackgroundService in Asp.net Core. </p>

<p>After doing some processing the BackgroundService initiates a shutdown by calling StopApplication.</p>

<p>Is there a way to shutdown the application and set the Kubernetes job to failed status when there is an exception in a BackgroundService?</p>

user2596613
<blockquote>
  <p>"Is there a way to shutdown the application and set the Kubernetes job
  to failed status ... ?"</p>
</blockquote>

<p>Yes, by anticipating that your application will exit with non-zero exit code when encountering an exception. That's the way how Kubernetes Job's final <a href="https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#handling-pod-and-container-failures" rel="nofollow noreferrer">status</a> is determined. </p>

<p>In other words, if container's process finishes with non-zero code, it causes Pod to terminate and eventually the Job status becomes <code>'Failed'</code>.</p>

<p>In case of stopping ASP.NET Core Application programmatically, with <code>'StopApplication()'</code> method, it exits with <code>'0'</code> exit code (example usage <a href="https://edi.wang/post/2019/3/7/restart-an-aspnet-core-application-programmatically" rel="nofollow noreferrer">here</a>).</p>

<p><strong>Possible solution:</strong></p>

<p>You program needs to handle an exception, even like graceful shutdown = <code>StopApplication()</code>, by explicitly setting an exit code to non-zero one beforehand (<code>[1,250]</code>).</p>

<p>Pseudo code:</p>

<pre><code>        catch (Exception ex)
        {
            _logger.LogError(ex, "Worker process caught exception");

            Environment.ExitCode = 1;
        }
        finally
        {
            applicationLifetime.StopApplication();
        }
</code></pre>

<p>based on example <a href="https://github.com/aspnet/Extensions/issues/2363#issuecomment-532719733" rel="nofollow noreferrer">here</a>.</p>
