在C#winform应用程序中捕获所有异常

时间:2018-09-26 22:20:12

标签: c# winforms exception events error-handling

在C#winform桌面应用程序中,我试图捕获所有可能出现在代码中的异常,这是我尝试过的:

/**
 * @Route("/account/listings/create", name="listing_create")
 */
public function createAction(Request $request)
{
    $r = sprintf('%09d', mt_rand(0, 1999999999));
    $form = $this->createForm(ListingType::class, null, [
        'currency' => $this->getParameter('app.currency'),
        'hierarchy_categories' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Category'), 'category', 'categories'),
        'hierarchy_locations' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Location'), 'location', 'locations'),
        'editId' => $r,
    ]);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $listing = $form->getData();
        $listing->setUser($this->getUser());

        try {
            $em = $this->getDoctrine()->getManager();
            $em->persist($listing);
            // I'd like to be able to get the value of an input field that is "editId" here
            $em->flush();
            $this->addFlash('success', $this->get('translator')->trans('Listing has been successfully created.'));
        } catch (\Exception $e) {
            $this->addFlash('danger', $this->get('translator')->trans('An error occurred when creating listing object.'));
        }

        return $this->redirectToRoute('listing_my');
    }

    return $this->render('FrontBundle::Listing/create.html.twig', [
      'form'  => $form->createView(),
      'editId' => $r]);
}

我在设备管理器中通过不带串行端口的窗体关闭事件附加“ COM6”来测试它,但是我只能看到Visual Studio using System; using System.Threading; using System.Windows.Forms; namespace Controller { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Run(new Form1()); } static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception"); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception"); } } } 报告

如何为Winform应用程序收集错误数据

3 个答案:

答案 0 :(得分:1)

在应用程序的一个点中捕获所有错误不是最佳实践。我建议您确定代码可能在哪里失败,并使用try / catch块来捕获特定的错误组。这样,您可以更好地控制应用程序,并且可以更好地识别代码的弱点。例如:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {

    try{
      //Put here your code
    }
    catch{
    }
}

一个通用的“异常”肯定无法帮助您或用户识别应用程序中可能的错误

答案 1 :(得分:1)

您可以使用try-catch捕获所有方法中的异常。在catch内部,您可以记录异常原因。

try
{
   // Your code that might throw an error
}
catch( Exception e )
{
   // What you want to do when the error is thrown
   Logger.WriteException(e);
}

我宁愿编写一个静态类'Logger'和'WriteException'方法来将异常记录到文本文件中。

public static class Logger
{
    public static void WriteException(Exception exception)
    {
        string filePath = @"D:\Error.txt";

        using (StreamWriter logWriter = new StreamWriter(filePath, true))
        {
            logWriter.WriteLine("Message :" + exception.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exception.StackTrace +
               "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            logWriter.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
        }
    }
}

有几种错误记录方法,您可以为您的应用程序使用合适的方法。您可以使用EventLog,Microsoft Logger等。

答案 2 :(得分:0)

实际上并不难做到。
我建议将用于处理异常的任何代码放入主窗体中,以保持program.cs尽可能整洁。

首先在您的Program.cs中输入

static class Program
{
    public static Form MainForm = null;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.ThreadException += Application_ThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        MainForm = new Form1();
        Application.Run(MainForm);
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        ((Form1)MainForm).Application_ThreadException(sender, e);
    }
}

然后在您的主表单中放置此

    public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        // All unhandled exceptions will end up here, so do what you need here

        // log the error
        // show the error
        // shut the application down if needed
        // ROLLBACK database changes 
        // and so on...
    }