Spring Security构建Rest服务-0300-Restful API异常处理
SpringBoot默认的错误处理机制:
一、测试需要的部分代码
(完整代码放在了github https://github.com/lhy1234/spring-security):
UserController:只对新增用户做测试,省略其他代码
@RestController
@RequestMapping("/user")
public class UserController { /**
* 创建
* @Description:
* //@RequestBody:json映射到java
* @Valid 和User类上的@NotBlank注解一起做校验
* BindingResult存储的是校验错误信息
* @param @param user
* @param @return
* @return User
* @throws
* @author lihaoyang
* @date 2018年2月24日
*/
@PostMapping
public User create(@Valid @RequestBody User user){ //,BindingResult errors 先屏蔽BindingResult让springboot做错误处理,不屏蔽就能正常响应200了 // if(errors.hasErrors()){
// errors.getAllErrors().stream()
// .forEach(error -> System.err.println(error.getDefaultMessage()));
// } user.setId("1");
System.err.println(user);
return user;
} //省略其他代码。。。 }
User类:使用valid注解校验
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView{}; //继承
private String id;
@NotBlank(message="用户名不能为空")
private String username;
@NotBlank(message="密码不能为空")
private String password;
@Past(message="生日只能是过去的日期")
private Date birthday;
//省略get set
}
一、对于进入controller之前就被打回的错误处理
1、对于url不存在的400错误处理
springboot对浏览器和app的请求,处理是不一样的:
1.1,使用浏览器,响应式的body一段html:
使用Springboot,启动服务,使用浏览器访问一个不存在的url后,出现html空白页:

浏览器发出的请求:请求头Content-Type:text/html;

1.2,使用chrome插件restlet client(https://restlet.com/modules/client/)模拟app访问:

使用restlet client模拟app访问不存在的url,响应体body是一个json:

图一
从上图可以看出,使用app发出的请求请求头是contentType是json类型
springboot错误处理类控制器 BasicErrorController代码片段:


这个控制器处理的url是 /error ,但是会根据请求头里类型的不同,做不同的处理,浏览器发的请求走上边的,返回时html;app发的请求,走下边的方法,返回是一个json。
这里提供了一种机制:同一个url,不同的情况做不同的处理。
上边是对url不存在的400错误的处理,从图一可以看出,springboot的响应信息很简单:
错误码 400,加上响应体body:
{
"timestamp": 1519608427470,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/xxx"
}
2,对于不符合校验规则的错误处理
User类的username和password是不能为空的,使用restlet client发出post请求,请求体为{},空的json,这样就不符合校验规则了(host是变量127.0.0.1):

响应头:

响应体:

会吧错误信息返回。
上边这两种情况,都是在进入controller之前就被spring打回的,一般我们需要在进入controller方法后,调用service过程中有异常来进行处理,下边模拟这种情况:
二、进入controller方法后发生了异常
在getInfo里直接抛出运行时异常模拟调用service发生错误:
/**
* 详情
* @Description: TODO
* @param @param id
* @param @return
* @return User
* @throws
* @author lihaoyang
* @date 2018年2月24日
*/
@GetMapping("{id:\\d+}") //{}里可以是正则,匹配数字
// @GetMapping("detail/{id}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable(value="id",required=true) String id){ throw new RuntimeException("query deltail interface has error!"); // System.err.println(id);
// User user = new User();
// user.setUsername("tom");
// user.setPassword("123456");
// user.setId("1");
// return user;
}
使用浏览器访问:

对于浏览器也可以自定义错误页面,在src/main/resources下新建resources/error目录,可以自定义错误页面,这个对于app访问是无效的,app还是返回json


模拟app访问:错误中只包含抛出的异常信息

大部分情况,这种springboot对rest服务做的错误处理已经够用了。
如果还不够用也可以自己定义错误处理机制:
三、自定义异常
自定义异常:
package com.imooc.exception; /**
* 用户不存在异常
* ClassName: UserNotExistException
* @Description: TODO
* @author lihaoyang
* @date 2018年2月26日
*/
public class UserNotExistException extends RuntimeException{
/**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = 1L; private String id; public UserNotExistException(String id){
super("user not exist!");
this.id = id;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} }
controller方法:
@GetMapping("{id:\\d+}") //{}里可以是正则,匹配数字
// @GetMapping("detail/{id}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable(value="id",required=true) String id){
// throw new RuntimeException("query deltail interface has error!");
throw new UserNotExistException(id);
// System.err.println(id);
// User user = new User();
// user.setUsername("tom");
// user.setPassword("123456");
// user.setId("1");
// return user;
}
此时浏览器访问,返回自定义的错误页

区别就在于app访问,exception类已经是自定义的了,但是异常信息message还不够详细,下面介绍怎么处理

统一异常处理类:
package com.imooc.web.controller; import java.util.HashMap;
import java.util.Map; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import com.imooc.exception.UserNotExistException; /**
* @ControllerAdvice:处理其他controller抛出的异常,都会到这里处理
*/
@ControllerAdvice
public class ControllerExceptionHandler { @ExceptionHandler(UserNotExistException.class)//处理哪个异常类
@ResponseBody //返回json
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码 500
public Map<String,Object> handlerUserNotExistException(UserNotExistException ex){
Map<String,Object> result = new HashMap<>();
//通过ex对象拿到异常信息
result.put("id", ex.getId());
result.put("message", ex.getMessage());
return result;
}
}

app访问,可以打印自己想要的异常信息。
Spring Security构建Rest服务-0300-Restful API异常处理的更多相关文章
- Spring Security构建Rest服务-1001-spring social开发第三方登录之spring social基本原理
OAuth协议是一个授权协议,目的是让用户在不将服务提供商的用户名密码交给第三方应用的条件下,让第三方应用可以有权限访问用户存在服务提供商上的资源. 接着上一篇说的,在第三方应用获取到用户资源后,如果 ...
- Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录
基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...
- Spring Security构建Rest服务-1202-Spring Security OAuth开发APP认证框架之重构3种登录方式
SpringSecurityOAuth核心源码解析 蓝色表示接口,绿色表示类 1,TokenEndpoint 整个入口点,相当于一个controller,不同的授权模式获取token的地址都是 /oa ...
- Spring Security构建Rest服务-1201-Spring Security OAuth开发APP认证框架之实现服务提供商
实现服务提供商,就是要实现认证服务器.资源服务器. 现在做的都是app的东西,所以在app项目写代码 认证服务器: 新建 ImoocAuthenticationServerConfig 类,@Ena ...
- Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架
基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...
- Spring Security构建Rest服务-0900-rememberMe记住我
Spring security记住我基本原理: 登录的时候,请求发送给过滤器UsernamePasswordAuthenticationFilter,当该过滤器认证成功后,会调用RememberMeS ...
- Spring Security构建Rest服务-0400-使用切片拦截rest服务
Restful API的拦截: 1,过滤器(Filter) 2,拦截器(Interceptor) 3,切片(Aspect) 1,过滤器 和传统javaweb一鸟样,例,记录controller执行时间 ...
- Spring Security构建Rest服务-1401-权限表达式
Spring Security 的权限表达式 用法,在自定义的BrowserSecurityConfig extends WebSecurityConfigurerAdapter 配置文件里,每一个a ...
- Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理
token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...
- Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理
token处理之一基本参数配置 处理token时间.存储策略,客户端配置等 以前的都是spring security oauth默认的token生成策略,token默认在org.springframe ...
随机推荐
- java redis基本操作
package com.redis; import java.util.ArrayList;import java.util.Iterator;import java.util.List;import ...
- (线段树)Balanced Lineup --POJ --3264
链接: 对于POJ老是爆,我也是醉了, 链接等等再发吧! http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82832#problem/G 只 ...
- 如何使用C++11实现C#属性概念设计
目录(原创博客,版权所有,转载请注明出处 http://www.cnblogs.com/feng-sc) 1.概述 2.C#属性的概念 2.1.简单示例代码介绍C#中的属性 2.2.C++实现效果 ...
- 从LSM-Tree、COLA-Tree谈到StackOverflow、OSQA
转自: http://blog.csdn.net/v_july_v/article/details/7526689 从LSM-Tree.COLA-Tree谈到StackOverflow.OSQA 作者 ...
- codeforces 702C Cellular Network 2016-10-15 18:19 104人阅读 评论(0) 收藏
C. Cellular Network time limit per test 3 seconds memory limit per test 256 megabytes input standard ...
- Java中对比两个对象中属性值[反射、注解]
在Java中通常要比较两个对象在修改前与修改后的值是否相同,一般我们采用的是反射技术获取对象的get方法[或其他的方法]获取值并做比较.如果系统将修改的属性名称也显示出来,这样就能更直观的显示类中的哪 ...
- jquery ui widgets-datepicker
jquery ui的用法就不在此讲述,直接进入jquery ui的窗体小部件(widgets)——datepicker. 相信很多像我这样子的菜鸟少年,如果同一个页面上有两个input文本输入框是用来 ...
- C#——调用C++的DLL 数据类型转换
/C++中的DLL函数原型为 //extern "C" __declspec(dllexport) bool 方法名一(const char* 变量名1, unsig ...
- C#深入浅出获取时间DateTime
首先,先了解微软.net里面的DateTime的DateTime.Now.DateTime.Now.Date.DateTime.Now.Day.DateTime.Now.DayOfWeek.DateT ...
- .Net Core in Docker - 在容器内编译发布并运行
Docker可以说是现在微服务,DevOps的基础,咱们.Net Core自然也得上Docker..Net Core发布到Docker容器的教程网上也有不少,但是今天还是想来写一写. 你搜.Net c ...