最近工作中涉及到捕捉AOP方法中抛出的异常。

想针对某一种异常做一个统一的处理器并封装好异常信息以JSON格式交给前端进行提示。

主要实现的话有以下几步:

1.编写自定义异常类

package com.laoxu.easyblog.exception;

/**
* @Description: 未授权异常
* @Author laoxu
* @Date 2019/7/3 21:51
**/
public class UnAuthorizedException extends RuntimeException{
private static final long serialVersionUID = 1L; private String errorCode;
private String errorMessage; public UnAuthorizedException(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
} public String getErrorCode() {
return errorCode;
} public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
} public String getErrorMessage() {
return errorMessage;
} public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

2.编写异常处理器

package com.laoxu.easyblog.framework;

import com.laoxu.easyblog.exception.UnAuthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @Description: 异常处理器
* @Author laoxu
* @Date 2019/7/3 22:14
**/
@ControllerAdvice
public class ExceptionsHandler {
@ResponseBody
@ExceptionHandler(UnAuthorizedException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public Result<String> customGenericExceptionHnadler(UnAuthorizedException exception){ //还可以声明接收其他任意参数
return ResultUtil.fail(Integer.valueOf(exception.getErrorCode()),exception.getErrorMessage());
}
}

3.包装返回信息

package com.laoxu.easyblog.framework;

/**
* 返回结果工具类
*
* @author xusucheng
* @create 2018-10-23
**/
public class ResultUtil {
public static boolean isOk(Result<?> result){
return null != result && result.getCode() == ErrorStatus.OK.getCode();
} public static <T> Result<T> ok(){
return new Result<T>(ErrorStatus.OK);
} public static <T> Result<T> ok(T data){
return new Result<T>(ErrorStatus.OK.getCode(), ErrorStatus.OK.getMessage(), data);
} public static <T> Result<T> fail(){
return new Result<T>(ErrorStatus.BAD_REQUEST).fail();
} public static <T> Result<T> status(ErrorStatus status){
return new Result<T>(status.getCode(), status.getMessage()).fail();
} public static <T> Result<T> fail(ErrorStatus status){
return new Result<T>(status.getCode(), status.getMessage()).fail();
} public static <T> Result<T> fail(String message){
return fail(ErrorStatus.BAD_REQUEST.getCode(), message, (T)null).fail();
} public static <T> Result<T> fail(int code, String message){
return new Result<T>(code, message).fail();
} public static <T> Result<T> fail(int code ,String message, T data){
return new Result<T>(code, message, data).fail();
} public static <T> Result<T> notfound(){
return new Result<T>(ErrorStatus.NOT_FOUND).fail();
} }

4.编写测试controller

package com.laoxu.easyblog.controller;

import com.laoxu.easyblog.exception.UnAuthorizedException;
import com.laoxu.easyblog.framework.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; /**
* @Description:
* @Author laoxu
* @Date 2019/7/3 22:09
**/
@Controller
@RequestMapping("/auth")
public class ExceptionController { @RequestMapping("/getLoginUser")
public Result<String> getLoginUser(){
throw new UnAuthorizedException("403","用户未授权!");
}
}

5.编写测试页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>测试页</title>
<script src="../js/jquery.min.js" th:src="@{/assets/js/jquery.min.js}"></script> </head>
<body> <button onclick="getLoginUser();">获取用户信息</button>
<script>
function getLoginUser(){
$.ajax({
url: "/blog/auth/getLoginUser",
type: "GET",
success: function (result) {
if (result.success) {
alert("获取成功!");
} else {
alert(result.code+":"+result.message);
} }
});
} </script>
</body>
</html>

6.测试

使用@ControllerAdvice统一处理自定义异常的更多相关文章

  1. @ExceptionHandler和@ControllerAdvice统一处理异常

    //@ExceptionHandler和@ControllerAdvice统一处理异常//统一处理异常的controller需要放在和普通controller同级的包下,或者在ComponentSca ...

  2. @ControllerAdvice与@ControllerAdvice统一处理异常

    https://blog.csdn.net/zzzgd_666/article/details/81544098(copy) 详细看此 所以结合上面我们可以知道,使用@ExceptionHandler ...

  3. Spring的@ExceptionHandler和@ControllerAdvice统一处理异常

    之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch try{ ..........}catch(Exception1 e){ ......... ...

  4. 统一异常处理@ControllerAdvice

    一.异常处理 有异常就必须处理,通常会在方法后面throws异常,或者是在方法内部进行try catch处理. 直接throws Exception 直接throws Exception,抛的异常太过 ...

  5. Spring Boot中Web应用的统一异常处理

    我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来 ...

  6. [转] Spring Boot中Web应用的统一异常处理

    [From] http://blog.didispace.com/springbootexception/ 我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供 ...

  7. spring boot:使接口返回统一的RESTful格式数据(spring boot 2.3.1)

    一,为什么要使用REST? 1,什么是REST? REST是软件架构的规范体系,它把资源的状态用URL进行资源定位, 以HTTP动作(GET/POST/DELETE/PUT)描述操作 2,REST的优 ...

  8. Spring Boot异常处理

    一.默认映射 我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局 ...

  9. 返回JSON格式(二十五)

    在上述例子中,通过@ControllerAdvice统一定义不同Exception映射到不同错误处理页面.而当我们要实现RESTful API时,返回的错误是JSON格式的数据,而不是HTML页面,这 ...

  10. 人人都是 API 设计师:我对 RESTful API、GraphQL、RPC API 的思考

    原文地址:梁桂钊的博客 博客地址:http://blog.720ui.com 欢迎关注公众号:「服务端思维」.一群同频者,一起成长,一起精进,打破认知的局限性. 有一段时间没怎么写文章了,今天提笔写一 ...

随机推荐

  1. [转帖]Always-on Profiling for Production Systems

    https://0x.tools/ 0x.tools (GitHub) is a set of open-source utilities for analyzing application perf ...

  2. [转帖]TNS-12535 TNS-00505的处理方法

    硬件说明: 操作系统版本:ORACLE LINUX 6.3  64位 数据库版本:11.2.0.3   64位 问题说明: 在检查数据库的alert日志的时候,发现大量的12170和TNS-12535 ...

  3. [转帖]Jmeter跨线程组传参

    https://www.cnblogs.com/a00ium/p/10462576.html   我们知道,同一线程组中可以通过"正则表达式提取器"获取其中一个取样器的响应结果中的 ...

  4. [转帖]高性能 -Nginx 多进程高并发、低时延、高可靠机制在百万级缓存 (redis、memcache) 代理中间件中的应用

    https://xie.infoq.cn/article/2ee961483c66a146709e7e861 关于作者 前滴滴出行技术专家,现任 OPPO 文档数据库 mongodb 负责人,负责 o ...

  5. 【转帖】nginx变量使用方法详解-3

    https://www.diewufeiyang.com/post/577.html 也有一些内建变量是支持改写的,其中一个例子是 $args. 这个变量在读取时返回当前请求的 URL 参数串(即请求 ...

  6. [转帖]5、kafka监控工具Kafka-Eagle介绍及使用

    https://zhuanlan.zhihu.com/p/628039102   # Apache Kafka系列文章 1.kafka(2.12-3.0.0)介绍.部署及验证.基准测试 2.java调 ...

  7. [转帖]setsockopt(setsockopt的使用方法及注意事项)

    http://xingzuo.aitcweb.com/9156453.html 1. setsockopt简介 setsockopt是一个系统调用函数,用于设置套接字选项.套接字是指通信的两个端点之间 ...

  8. [转帖]队列深度对IO性能的影响

    https://www.modb.pro/db/43710 几年前一个客户的Oracle数据库经常HANG,老白帮他分析了一下,结论是存储老化,性能不足以支撑现有业务了.正好用户手头有个华为S5600 ...

  9. ggrep让多行日志-无处遁形!

    相信大家都很喜欢用grep指令,查一下项目中有没有出错的,然后通过logid搜索相关出错的日志和一些关键参数,但是在多行日志的情况下就很难处理了,比如okhttp拦截器中分别打印了url,param和 ...

  10. empty来显示暂无数据简直太好用,阻止用户复制文本user-select

    element-ui表格某一列无数据显示-- 很多时候,表格的某一列可能是没有数据的. 空着了不好看,ui小姐姐会说显示 -- 这个时候,小伙伴是怎么做的呢? 使用循环来判断是否为空,然后赋值为-- ...