spring - java有什么方法可以捕获程序异常的?然后中断程序,发送信息给前端
怪我咯
怪我咯 2017-04-18 09:40:43
0
3
863

我现在有这个问题:

我在这里想获取整数的,但是文件中出现了小数,那么就有异常了这里,如何抓获这个异常呢?try catch?

    cell.setCellType(Cell.CELL_TYPE_STRING);
    result = cell.getStringCellValue();
java.lang.NumberFormatException: For input string: "103.12"

当出现这个问题的时候,程序是中断了,但是只是在控制台输出这个信息。如果用什么方法捕获这些错误,然后发送信息给前端呢?

现在出现这个错误,前端就显示卡死状态。除非关闭页面。

控制台也停了:

只是tomcat自己获取错误:


                    try {

                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        result = cell.getStringCellValue();

                    } catch (NumberFormatException e) {

                        e.printStackTrace();

                    }

抓获异常,怎么抓呢?在哪里返回异常信息给前端呢?

============================================================

请问呢,如何在后端java中获取response呢?我用的是spring和springmvc。更具体说:怎么在catch上面获得response,并且输入信息呢?

============================================================

    try {

                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        result = cell.getStringCellValue();

                    } catch (NumberFormatException e) {

                        System.out.println("转换发生如下错误:"+e.getMessage());
                        try {

                            String message = e.getMessage();
                            response.getWriter().write(message);


                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();

                    }

我都这样写了,还是在控制台什么没输出。System.out.println("转换发生如下错误:"+e.getMessage());这句代码没用啊!!!停住在这里....

怪我咯
怪我咯

走同样的路,发现不同的人生

répondre à tous(3)
迷茫

1 Vous interceptez cette exception
2 Dans votre catch, vous renvoyez un message à réponse.getOutputStream ou réponse.getWriter
3 Votre js front-end (si vous utilisez ajax) lit l'étape 2 La sortie est fourni au front-end ; si vous êtes jsp, alors out.print(xxx);

in jsp
巴扎黑

Utilisez évidemment Java spécifiquement pour intercepter les exceptions try catch

public static boolean test() {
    try {
        int i = 10 / 0; // 抛出 Exception,后续处理被拒绝
        System.out.println("i vaule is : " + i);
        return true;   // Exception 已经抛出,没有获得被执行的机会
    } catch (Exception e) {
        System.out.println(" -- Exception --");
        return catchMethod();  // Exception 抛出,获得了调用方法的机会,但方法值在 finally 执行完后才返回
    }finally{
        finallyMethod();  // Exception 抛出,finally 代码块将在 catch 执行 return 之前被执行
    }
}
洪涛

Essayez ça ?

@ControllerAdvice
public class GlobalExceptionHandlingControllerAdvice {

    protected Logger logger;

    public GlobalExceptionHandlingControllerAdvice() {
        logger = LoggerFactory.getLogger(getClass());
    }

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
    /* . . . . . . . . . . . . . EXCEPTION HANDLERS . . . . . . . . . . . . . . */
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

    /**
     * Convert a predefined exception to an HTTP Status code
     */
    @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
    // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void conflict() {
        logger.error("Request raised a DataIntegrityViolationException");
        // Nothing to do
    }

    /**
     * Convert a predefined exception to an HTTP Status code and specify the
     * name of a specific view that will be used to display the error.
     * 
     * @return Exception view.
     */
    @ExceptionHandler({ SQLException.class, DataAccessException.class })
    public String databaseError(Exception exception) {
        // Nothing to do. Return value 'databaseError' used as logical view name
        // of an error page, passed to view-resolver(s) in usual way.
        logger.error("Request raised " + exception.getClass().getSimpleName());
        return "databaseError";
    }

    /**
     * Demonstrates how to take total control - setup a model, add useful
     * information and return the "support" view name. This method explicitly
     * creates and returns
     * 
     * @param req
     *            Current HTTP request.
     * @param exception
     *            The exception thrown - always {@link SupportInfoException}.
     * @return The model and view used by the DispatcherServlet to generate
     *         output.
     * @throws Exception
     */
    @ExceptionHandler(SupportInfoException.class)
    public ModelAndView handleError(HttpServletRequest req, Exception exception)
            throws Exception {

        // Rethrow annotated exceptions or they will be processed here instead.
        if (AnnotationUtils.findAnnotation(exception.getClass(),
                ResponseStatus.class) != null)
            throw exception;

        logger.error("Request: " + req.getRequestURI() + " raised " + exception);

        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", exception);
        mav.addObject("url", req.getRequestURL());
        mav.addObject("timestamp", new Date().toString());
        mav.addObject("status", 500);

        mav.setViewName("support");
        return mav;
    }
}

Code source

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal