java自定义异常并处理异常

自定义异常:

/**
 * 自定义异常
 *
 * @author ruoyi
 */
@Data
public final class MyException extends RuntimeException
{
    private Integer status = ExceptionCode.SERVICEEXCEPTION.getCode();


    public MyException() {

    }

    public MyException(ExceptionCode status,String message) {

        super(status.getCode()+"&"+message);
        this.status = status.getCode();
    }


    public MyException(Throwable cause) {
        super(cause);
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

    public MyException(String message, Throwable cause,
                       boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}
/**
 * 自定义异常状态
 * 
 * @author ruoyi
 */
public enum ExceptionCode
{
    TOKENEXCEPTION(40000),//登录TOKEN异常
    SERVICEEXCEPTION(41000),//业务异常(包括参数)
    AUTHEXCEPTION(42000);//权限异常

    private final Integer code;


    ExceptionCode(Integer code)
    {
        this.code = code;

    }
    public Integer getCode()
    {
        return code;
    }

}

自定义异常处理:

/**
 * 自定义异常处理
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

	@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
	public void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		//返回给前端的信息
		Map<String, Object> map = new HashMap<String, Object>();
		String message = ex.getMessage();
		Integer status = 500;

		if(ex.getClass().equals(MyException.class)){
			//是自定义异常
			String[] str = message.split("&");
			status = MyUtil.convertToInt(str[0], 500);
			message = str[1];
		}else{
			message = "系统错误";
		}

		if (status.equals(500)) {
			System.out.println("非业务异常,请查看错误日志");
			log.error(MyExceptionUtil.getExceptionAllinformation(ex));
		} else {
			System.out.println("错误" + status + ":" + message);
		}

		map.put("status", status);
		map.put("message", message);
		request.setAttribute("errorMap", map);
		response.setHeader("Content-Type", "application/json");
		response.setStatus(403);
		MyUtil.writeObjectToClient(map, response);
	}
}
  /**
     * 异步传输Json数据
     *
     * @param obj
     * @param response
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     * @author wzd
     * @description
     * @date 2013-2-28
     */
    public static void writeObjectToClient(Object obj, HttpServletResponse response) {

        String jsonStr = JSON.toJSONString(obj);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().print(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  /**
     * 获得异常的字符串形式信息
     * @param e 要打印的异常
     * @return
     */
    public static String getExceptionAllinformation(Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        e.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return ret;
    }

结束:

这样只要

throw new MyException(ExceptionCode.SERVICEEXCEPTION,"");

就能返回异常信息给前端了,前端就能统一进行异常处理了。

你可能感兴趣的:(java,java-ee,json)