小白第二次写博客,在这里记录下个人认为比较重要的知识整理,有错求评论指出.
1.springboot处理全局异常的常用方法
1.1(非必要) 异常信息实体类
主要用户包装异常信息.
public class ErrorResponse{
private String message;
private Stirng errorTypeName;
public ErrorResponse(){
}
public ErrorResponse(Exception e){
this(e.getClass().getName(),e.getMessage());
}
public ErrorResponse(String errorTypeName,String message){
this.errorTypeName=errorTypeName;
this.message=message;
}
..getter/setter方法..
}
1.2自定义异常类型(通用)
一般情况下可以直接处理RuntimeException异常,但是可以使用自定义异常类型细粒度化.
如定义一个资源未找到异常,如下
public class ResourceNotFoundException entends RuntimeException{
private String message;
public ResourceNotFoundException(){
super();
}
public ResourceNotFoundException(String message){
super(message);
this.message=message;
}
@Override
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message=message;
}
}
1.3新建异常处理类
类上加@ControllerAdvice注解就会变成全局异常处理类,加入属性assignableTypes = {ExceptionController.class}可只处理特定类抛出的异常.
@ControllerAdvice
public class BaseExceptionHandler {
ErrorResponse resourceNotFoundResponse = new ErrorResponse(new ResourceNotFoundException("资源未找到"))
/**
* 全局异常处理
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseEntity<ErrorResponse> error(Exception e){
e.printStackTrace();
if(e instanceof ResourceNotFoundException){
return ResponseEntity.status(404).body(resourceNotFoundResponse );
}
return null;
}
}
1.4 ResponseStatusException
这是spring的web包提供的通用异常,可以很简单的将异常映射为状态码
提供了三个构造方法以及对应的get方法:
public ResponseStatusException(HttpStatus status) {
this(status, (String)null, (Throwable)null);
}
public ResponseStatusException(HttpStatus status, @Nullable String reason) {
this(status, reason, (Throwable)null);
}
public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) {
super((String)null, cause);
Assert.notNull(status, "HttpStatus is required");
this.status = status;
this.reason = reason;
}
使用这个类可以简单处理异常,如下例子:
@GetMapping("/aaa")
@public void doThrowException(){
throw new ResponseStatusException(HttpStatus.Not_Found,"资源未找到",new ResourceNotFoundException ());
}
这里只是简单应用,具体应用不多讲.
这位大神的例子可以参考
https://blog.csdn.net/qq_20282955/article/details/104916118
2.Json数据处理
2.1过滤json数据
public class school{
private Integer id;
private String name;
private String address;
@JsonIgnore
pirvate List<Student> students = new ArrayList<>();
}
@JsonIgnore该注解作用于类的属性,表示生成json时过滤该属性.
2.2格式化json数据
@JsonFormat(shape = JsonFormat.Shape.STRING , pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT")
private Date date;
当自动注入属性时,会按照指定格式转换
3.测试注解
@SpringbootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("webtest")
public class WebTest{
@Test
@Transactional
@WithMockUser(username= "user-id-13712166666",authorities = "ROLE_ADMIN")
}
@SpringbootTest(webEnvironment =RANDOM_PORT)
该注解表示会生成随机端口号
@ActiveProfiles声明有效的spring配置文件
@Test
标注该方法为测试方法
@Transactional
测试该方法时回滚,避免污染数据库
@WithMockUser
spring security提供,用于模拟访问的用户为真实有效的用户,并且具有特定权限