4、spring boot + Maven + Restful Exception异常跳转和自定义错误

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29451823/article/details/82761795
  1. 错误html页面(会根据错误自动跳转到页面)
    在这里插入图片描述

  2. 如果报错运行时异常会跳转到500.html
    在这里插入图片描述

  3. 使用Restlet Client来测试
    返回内部默认处理结果

  4. 自定义UserNotExistException类

package com.imooc.exception;

public class UserNotExistException extends RuntimeException {

	/**
	 * 序列号
	 */
	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;
	}
	
	
}

  1. 加载错误类的注解类
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;

/**
 * 加载自定义错误
 * @author caijiajun
 * @date   2018年9月11日
 */
@ControllerAdvice
public class ControllerExceptionHandler {
	
	@ExceptionHandler(UserNotExistException.class)//加载自定义错误类
	@ResponseBody//返回json格式
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//表明注解的类型
	public Map<String, Object> handlerUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}
	
}

  1. 模拟错误发生
	@GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getInfo(@PathVariable(name = "id") String id) {
	throw new UserNotExistException(id);
//		System.out.println("进入getInfo服务");
//		User user = new User();
//		user.setUsername("tom");
//		return user;
	}
  1. 用Restlet Client 测试
    返回对应存放在result的值
  2. @JsonView的用法
    @JsonView返回实体类中指定字段属性
    在这里插入图片描述
    控制controller
	@GetMapping
	//指定参数名称@RequestParam(value = "usename", required = false ,defaultValue = "tom")
	@JsonView(User.UserSimpleView.class)
	@ApiOperation(value = "用户查询服务")
	public List<User> query(UserQueryCondition condition,@PageableDefault(page = 2 ,size =17, sort = "asc") Pageable pageable) {
		//反射的一个tostring工具
		System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); 
		System.out.println(pageable.getPageSize());
		System.out.println(pageable.getPageNumber());
		System.out.println(pageable.getSort());
		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}

9.用Restlet Client 测试
在这里插入图片描述
注意:子接口如果继承父接口,那么返回的字段也包括父接口上添加的字段

猜你喜欢

转载自blog.csdn.net/qq_29451823/article/details/82761795
今日推荐