1. 程式人生 > >170621、springboot編程之全局異常捕獲

170621、springboot編程之全局異常捕獲

json.js https handle style lan erro stack oca exce

1、創建GlobalExceptionHandler.java,[email protected],[email protected](value = Exception.class),Exception.class表示攔截所有的異常信息


package com.rick.common.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.IOUtils;
import com.rick.common.ResultJson;
import com.rick.common.exception.BusinessException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
System.out.println("=====================全局異常信息捕獲=======================");

String msg;
if(ex instanceof BusinessException){
msg = ex.getMessage();
} else {
msg = "操作異常!";
}
ex.printStackTrace();
PrintWriter out = null;
try {
out = response.getWriter();
out.print(JSON.toJSON(ResultJson.buildFailInstance(msg)).toString());
} catch(Exception e){
e.printStackTrace();
} finally {
IOUtils.close(out);
}

return null;
}
}

2、測試異常信息,在 HelloController.java中制造異常信息

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        System.out.println(1/0);//制造異常信息
        return "Hello World!";
    }
}

3、效果展示

訪問http://localhost:8080/hello,後臺拋出異常信息

技術分享

頁面展示效果

技術分享

170621、springboot編程之全局異常捕獲