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异常处理的更多相关文章

  1. Spring Security构建Rest服务-1001-spring social开发第三方登录之spring social基本原理

    OAuth协议是一个授权协议,目的是让用户在不将服务提供商的用户名密码交给第三方应用的条件下,让第三方应用可以有权限访问用户存在服务提供商上的资源. 接着上一篇说的,在第三方应用获取到用户资源后,如果 ...

  2. Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录

    基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...

  3. Spring Security构建Rest服务-1202-Spring Security OAuth开发APP认证框架之重构3种登录方式

    SpringSecurityOAuth核心源码解析 蓝色表示接口,绿色表示类 1,TokenEndpoint 整个入口点,相当于一个controller,不同的授权模式获取token的地址都是 /oa ...

  4. Spring Security构建Rest服务-1201-Spring Security OAuth开发APP认证框架之实现服务提供商

    实现服务提供商,就是要实现认证服务器.资源服务器. 现在做的都是app的东西,所以在app项目写代码  认证服务器: 新建 ImoocAuthenticationServerConfig 类,@Ena ...

  5. Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架

    基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...

  6. Spring Security构建Rest服务-0900-rememberMe记住我

    Spring security记住我基本原理: 登录的时候,请求发送给过滤器UsernamePasswordAuthenticationFilter,当该过滤器认证成功后,会调用RememberMeS ...

  7. Spring Security构建Rest服务-0400-使用切片拦截rest服务

    Restful API的拦截: 1,过滤器(Filter) 2,拦截器(Interceptor) 3,切片(Aspect) 1,过滤器 和传统javaweb一鸟样,例,记录controller执行时间 ...

  8. Spring Security构建Rest服务-1401-权限表达式

    Spring Security 的权限表达式 用法,在自定义的BrowserSecurityConfig extends WebSecurityConfigurerAdapter 配置文件里,每一个a ...

  9. Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理

    token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...

  10. Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理

    token处理之一基本参数配置 处理token时间.存储策略,客户端配置等 以前的都是spring security oauth默认的token生成策略,token默认在org.springframe ...

随机推荐

  1. MAC安装远程工具Securecrt的破解方式(详细有图)

    想要实现mac的远程连接功能,本来想使用终端的,但是终端的很多功能是欠佳的,所以决定安装一款,像windows的xshell一样好的软件,所以选择了这款Securecrt. 首先准备两个东西,一个是S ...

  2. faceswap linux安裝教程

    http://www.mamicode.com/info-detail-2602743.html https://blog.csdn.net/sinat_26918145/article/detail ...

  3. Codeforces805D. Minimum number of steps 2017-05-05 08:46 240人阅读 评论(0) 收藏

    D. Minimum number of steps time limit per test 1 second memory limit per test 256 megabytes input st ...

  4. 循环读取list 的几种方法?

    1.最常用的方法.循环找出该位子的list元素for(int i = 0;i < list.size(); i ++){System.out.println(list.get(i));}2.利用 ...

  5. iOS Development和iOS Distribution有什么区别

    http://zhidao.baidu.com/link?url=T9od33JuA7jjxzfyV-wOjuVLSNUaqpc9aoCu2HjfYfHBuRLW1CNDii0Bh9uvG6h-GeJ ...

  6. jenkins构建随笔

    /t:Rebuild/p:Configuration=Debug/p:VisualStudioVersion=12.0/p:WebProjectOutputDir=E:\wwwroot\3.WCFSv ...

  7. Quartz.net 起步

    安装 Quartz 程序包 使用 nuget 命令行安装 Quartz: Install-Package Quartz 如果使用 JSON 序列化,使用 nuget 安装 Quartz.Seriali ...

  8. asp.net-分析器错误消息: 服务器标记的格式不正确。

    大多数都是引号造成的 错误: <asp:LinkButton ID="btnRefund" runat="server" CommandName=&quo ...

  9. C#默认以管理员身份运行程序实现代码

    using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; names ...

  10. jQuery ajax的jsonp跨域请求

    一直在听“跨域跨域”,但是什么是跨域呢?今天做了一些了解.(利用jQuery的jsonp) jQuery使用JSONP跨域 JSONP跨域是利用script脚本允许引用不同域下的js实现的,将回调方法 ...