如何将服务端的错误返回到客户端
比如:我现在用java写的sql代码插入重复值了?这时(下方)e.printStackTrace()会在服务端报错,我现在想要将这个错误截取过来,然后传回客户端进行提示,希望高手赐教!catch (Exception e) {
e.printStackTrace();

解决方案 »

  1.   

    你的客户端是什么。?????
    你可以在catch (Exception e) { 
    在这里把值赋给客户端
    }
      

  2.   

    我的客户端是IE,我现在希望的是能把e.printStackTrace()这里的值获取过来,转成字符串,返回给客户端;
    catch (Exception e) { 
    在这里把值赋给客户端
    }
    这样直接写的话,觉得会把异常写死,有可能不是违反唯一性约束,这时返回客户端就不能得到正确的结果
      

  3.   

    catch (Exception e) {
    StringWriter sw=new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    System.out.println(sw.toString());
    }
    利用StringWriter截获print堆栈输出,然后用StringWriter.toString方法返回所有截获字符串
    得到字符串后将其发送到客户端即可。
      

  4.   

    郁闷,发了二次都没发上来,还把我写的一大堆内容清空,俺要像csdn提个需求了,一旦发送失败,不能清空我的内容;谢谢楼上的,我刚才简单试了一下,感觉e.printStackTrace中异常,并没有放到sw中
    但只是简单试了一下,可能还是我自己的问题,一会儿有时间,再研究一下。下方是我的代码
    package jy;import java.sql.*;
    import java.io.*;public class test { private static Connection con = null; public static void ConDB(String user, String pwd, String DBName,
    String ServerAddress) {
    try {
    String driver = "net.sourceforge.jtds.jdbc.Driver";
    Class.forName(driver).newInstance();
    String url = "jdbc:jtds:sqlserver://" + ServerAddress + "/"
    + DBName;
    con = DriverManager.getConnection(url, user, pwd);
    System.out.println("connection success!");
    } catch (Exception e) {
    StringWriter sw=new StringWriter(); 
    e.printStackTrace(new PrintWriter(sw)); 
    }
    }
    public static void jytest() {
    PreparedStatement pstmt = null;
    Statement stmt = null;
    String sql = null;
    try {
    //int AwokeDayInt = Integer.parseInt(AwokeDay);
    ConDB("xx","xx","x5_hr","xx.xx.1.1xx6:1433");
    sql = "INSERT INTO test(fID, fAge, fName, fSex) VALUES (121212, 1, 2, 2)";
    stmt = con.createStatement();
    System.out.println(sql);
    pstmt = con.prepareStatement(sql);
    pstmt.executeUpdate();

    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    if (stmt != null) {
    try {
    stmt.close();
    con.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }}
      

  5.   

    自己写错了,代码写错地方 ,丢脸啊!谢谢spiniper